【问题标题】:How to store multiple word in one string without replacing old words in java如何在一个字符串中存储多个单词而不替换java中的旧单词
【发布时间】:2017-01-22 14:53:43
【问题描述】:

我是 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 上被替换和覆盖......所以最后我只有可以得到 msg 3 字符串...

感谢您的帮助

【问题讨论】:

  • 你的意思是像anothertemp += temp;吗?
  • @Orin2005 不,我的意思是我希望所有意图的字符串味精都在一个字符串中
  • 你能多说一下intent的内容吗?您的消息是否总是由诸如“msg”之类的常量子字符串分隔?
  • @markspace 我在我的编辑中添加了意图,请检查它..它是通知侦听器的一部分。你可以在这里找到它link

标签: java android string android-intent text


【解决方案1】:

当向旧字符串追加一个新字符串时,我们使用 += 运算符。所以你可以使用

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

虽然,您可能会遇到一种叫做变量作用域的东西。例如,NotificationReceiver 类中的方法 onReceive 中的变量 tempanotherTemp 将在每次调用该方法时被“清空”并重写。

为了防止这种情况,您必须将变量移出方法。使它们成为实例变量可能会起作用。有关变量范围的更多信息,请参阅this link

【讨论】:

  • 谢谢,但我的问题是另外一回事。考虑到我们有 3 个通知“msg1”、“msg2”和“msg3”,在 NotificationReceiver 类中的方法 onReceive 中将一一发布字符串(一个接一个)当 msg1 字符串发布时,它将发布 msg2 字符串。它不会同时发布所有这些味精……这就是将要发生的事情;它将发布通知 msg 1 字符串,然后将发布 msg2 字符串,它将在 msg 1 上被替换和覆盖,然后它将发布 msg 3,它将在 msg2 上被替换和覆盖......所以最后我只有可以得到 msg 3 字符串...
  • 丹尼斯是绝对正确的。使您的字符串变量成为实例变量或静态变量。
【解决方案2】:

String x = "Hello," + System.lineSeparator() + "there";

查看其他解决方案 Java String new line

【讨论】:

  • 我知道如何插入新行,但我的问题是字符串会被替换,旧的会丢失。我需要避免替换单词
猜你喜欢
  • 2011-10-08
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 2020-09-01
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多