我一直在尝试构建一个while循环来循环遍历字符串,当它包含我正在寻找的'模式'时。字符串是一个局部变量,在while循环上方声明,我无法在while循环中对其进行子串,因此每个连续循环都会查看字符串的下一部分。
如果我能解决这个问题,我将不胜感激
这是代码;只是你有这个想法,在线列表通常作为数组列表输出,例如[阿德里安,鲍勃,巴迪]
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);
}
答案 0 :(得分:1)
String在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
答案 1 :(得分:1)
字符串是不可变的。这意味着substring
不会修改字符串本身,而是返回一个新的字符串对象。所以你应该使用:
modifiedOnlineList = modifiedOnlineList.substring(tempFirstOccurence + 2);
答案 2 :(得分:0)
modifiedOnlineList.substring()只返回原始的modifiedOnlineList的子字符串,它不会修改modifiedOnlineList。