1

我一直在尝试构建一个 while 循环,以在字符串包含我正在寻找的“模式”时循环该字符串。该字符串是一个局部变量,在 while 循环上方声明,我无法在我的 while 循环中对其进行子字符串化,因此每个连续循环都将查看字符串的下一部分。

我将不胜感激有关如何解决此问题的任何帮助

这是代码;就这样你知道 onlineList 通常作为数组列表输出,例如 [Adrian, Bob, Buddy]

                String onlineList = networkInput.nextLine();
                //Declare a local variable for modified online list, that will replace all the strings that contain ", " "[" and "]"
                String modifiedOnlineList = onlineList.replaceAll("\\, ", "\n").replaceAll("\\[", "").replaceAll("\\]", "");
                //Loop the modifiedOnlineList string until it contains "\n"
                while (modifiedOnlineList.contains("\n")) {
                    //A local temporary variable for the first occurence of "\n" in the modifiedOnlineList
                    int tempFirstOccurence = modifiedOnlineList.indexOf("\n");
                    //Obtain the name of the currently looped user
                    String tempOnlineUserName = modifiedOnlineList.substring(0, tempFirstOccurence);
                    //Substring the remaining part of the string.
                    modifiedOnlineList.substring(tempFirstOccurence + 2);
                    System.out.println(modifiedOnlineList);

                }
4

3 回答 3

1

字符串在java中是不可变的

 modifiedOnlineList = modifiedOnlineList.substring(tempFirstOccurence + 2);

您必须接收方法返回的 String对象 substring

 modifiedOnlineList.substring(tempFirstOccurence + 2);
 System.out.println(modifiedOnlineList);   // still old value 

当你收到

 modifiedOnlineList = modifiedOnlineList.substring(tempFirstOccurence + 2);
 System.out.println(modifiedOnlineList);   // now re assigned to substring value 
于 2013-10-25T14:55:17.790 回答
1

字符串是不可变的。这意味着substring不会修改字符串本身,而是返回一个新的字符串对象。所以你应该使用:

modifiedOnlineList = modifiedOnlineList.substring(tempFirstOccurence + 2);
于 2013-10-25T14:56:10.920 回答
0

modifiedOnlineList.substring() 只返回原始 modifiedOnlineList 的子字符串,它不修改 modifiedOnlineList。

于 2013-10-25T14:56:59.963 回答