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.
Strings in Java are immutable. I believe you want to do this:
String str = "hello";
str = str.substring(1);
System.out.println(str);
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.
您没有保存对字符串所做的更改。
str=str.substring(1);
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.
You can directly put it in the .println(..)
String str = "hello";
System.out.println(str.substring(1));
but str will remain unchanged.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.