Java在while循环内对局部变量进行子字符串化 [英] Java substring a local variable inside a while loop

查看:28
本文介绍了Java在while循环内对局部变量进行子字符串化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been trying to construct a while loop for looping through a string when it contains a 'pattern' i'm looking for. The string is a local variable, declared just above the while loop and I am unable to substring it within my while loop, so that each consecutive loop will look at the next part of the string.

如果您能帮助我解决这个问题,我将不胜感激

I would appreciate any help on how I could solve this problem

这是代码;只是让您知道 onlineList 通常作为数组列表输出出现,例如[阿德里安、鲍勃、巴迪]

Here's the code; just so u have the idea the onlineList usually comes as array list output e.g. [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);

                }

推荐答案

String is immutable in java

String is immutable in java

 modifiedOnlineList = modifiedOnlineList.substring(tempFirstOccurence + 2);

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

You have to receive the new String Object returned by substring method.

 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 

这篇关于Java在while循环内对局部变量进行子字符串化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆