Java substring a local variable inside a while loop

前端 未结 3 1200
余生分开走
余生分开走 2021-01-24 10:41

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 th

相关标签:
3条回答
  • 2021-01-24 11:23

    Strings are immutable. That means that substring does not modify the string itself, but returns a new string object. So you should use:

    modifiedOnlineList = modifiedOnlineList.substring(tempFirstOccurence + 2);
    
    0 讨论(0)
  • 2021-01-24 11:25

    String is immutable in java

     modifiedOnlineList = modifiedOnlineList.substring(tempFirstOccurence + 2);
    

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

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

    when you receive that

     modifiedOnlineList = modifiedOnlineList.substring(tempFirstOccurence + 2);
     System.out.println(modifiedOnlineList);   // now re assigned to substring value 
    
    0 讨论(0)
  • 2021-01-24 11:32

    modifiedOnlineList.substring() just returns a substring of the original modifiedOnlineList, it doesn't modify modifiedOnlineList.

    0 讨论(0)
提交回复
热议问题