繁体   English   中英

如何在一个字符串中存储多个单词而不替换Java中的旧单词

[英]How to store multiple word in one string without replacing old words in java

我在android和java中是新的,我有这个意图

String temp  = intent.getStringExtra("msg");

并连续返回多个单词,例如“ msg a”,“ msg b”,“ msg c” ...,我想将所有这些单词存储到另一个字符串中

这就是我尝试过的

String anothertemp = temp;

但问题是它只存储了最后一个单词“ msg c”。 我的意思是它将用旧单词替换并覆盖新单词

我想将所有这些单词存储在一个新字符串中,并将每个单词存储在这样的新行中

msg a
msg b 
msg c

顺便说一下,我也已经尝试过这些

String temp  = intent.getStringExtra("msg")+ "\n" ;
&
String anothertemp = temp+ "\n";

仍然有同样的问题。 对不起,我英语不好

编辑一个

这是我的意图

    class NLServiceReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getStringExtra("command").equals("list")){

            int i=1;
            for (StatusBarNotification sbn : NLService.this.getActiveNotifications()) {
                Intent i2 = new  Intent("notificationmsg");
                i2.putExtra("msg",i +" " + sbn.getPackageName() + "\n");
                sendBroadcast(i2);
                i++;
            }

        }

    }
}

这就是我所说的

class NotificationReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {

        String temp = intent.getStringExtra("msg") + "\n";
String anothertemp = temp;
    }
}

编辑两个

考虑我们有3个通知“ msg1”,“ msg2”和“ msg3”,在NotificationReceiver类的onReceive方法中,当msg1字符串发布时,它将一个接一个地(一个接一个地)发布字符串,然后它将发布msg2字符串。 它不会在同一时间将所有这些消息一起发布..这将发生; 它将发布通知msg 1字符串,然后发布msg2字符串,它将在msg 1上被替换并覆盖,然后它将发布msg 3并将被替换并在msg2上覆盖...所以最后我只可以得到味精3字符串...

谢谢你的帮助

字符串x =“ Hello,” + System.lineSeparator()+“ there”;

有关其他解决方案,请查看Java String换行

当在旧字符串后添加新字符串时,我们使用+ =运算符。 所以你可以使用

String str = "foo";
str += "bar"; //the value of str will be 'foobar' now

虽然,您可以面对称为可变范围的东西。 例如,在anotherTemp该方法onReceiveNotificationReceiver类中onReceive方法中的变量tempanotherTemp将被“清空”并重写。

为了避免这种情况,您将不得不将变量移出方法。 使它们成为实例变量可能会起作用。 有关可变作用域的更多信息,请参见此链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM