Java substring not working

淺唱寂寞╮ 提交于 2021-02-16 21:26:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!