问题
Forgive me, I'm new to Java and have an extremely basic question. I have a string and want a substring of it, for example:
String str = "hello";
str.substring(1);
System.out.println(str);
Instead of getting "ello" I get the original "hello", any idea why this is? Thanks.
回答1:
Strings cannot be changed in Java, so you will need to re-assign the substring as such:
str = str.substring(1)
as opposed to calling the method by itself.
回答2:
Strings in Java are immutable. I believe you want to do this:
String str = "hello";
str = str.substring(1);
System.out.println(str);
回答3:
You aren't saving the changes done on the string.
str=str.substring(1);
回答4:
You need to save the substring into a new variable (or the old one if you prefer). Something like this should do the trick:
String str = "hello";
String strSub = str.substring(1);
System.out.println(strSub);
For people reading this post, remember that substring(1) means take the substring starting at char 1 and going until the end of the string.
回答5:
You can directly put it in the .println(..)
String str = "hello";
System.out.println(str.substring(1));
but str will remain unchanged.
来源:https://stackoverflow.com/questions/11130422/java-substring-not-working