簡體   English   中英

Java在while循環內將本地變量子字符串化

[英]Java substring a local variable inside a while loop

我一直在嘗試構造一個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);

                }

字符串在Java中是不可變的

 modifiedOnlineList = modifiedOnlineList.substring(tempFirstOccurence + 2);

您必須接收substring方法返回的 String對象。

 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 

字符串是不可變的。 這意味着substring不會修改字符串本身,而是返回一個新的字符串對象。 因此,您應該使用:

modifiedOnlineList = modifiedOnlineList.substring(tempFirstOccurence + 2);

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM