字符串修剪功能不起作用 [英] string trim function is not working
问题描述
我了解到 string.trim()
删除了前导和尾随空格.但是在我的情况下,它无法正常工作,我正在尝试使用以下代码,但输出具有前导和尾随空格.但是我的期望是文本没有开头和结尾的空格.这是我的代码.
I learned string.trim()
removes leading and trailing spaces. But in my case its not working i am trying below code but output is with leading and trailing space. But my expectation is text without leading and trailing space. Here is my code.
String s = " Hello Rais ";
s += " Welcome to my World ";
s.trim( );
System.out.println(s);
请帮助我
推荐答案
您需要将 trim
的结果重新分配回 s
:
You need to re-assign the result of trim
back to s
:
s = s.trim();
请记住, Java中的字符串是不可变的 ,因此几乎所有String类方法将创建并返回新的字符串,而不是修改字符串就位.
Remember, Strings in Java are immutable, so almost all the String class methods will create and return a new string, rather than modifying the string in place.
尽管这是题外话,但是(正如我在几乎
那里所说的),值得知道的是,此规则的例外是在创建相同长度的 substring
时,或者方法在任何时候返回具有相同值的字符串,这将被优化并且不会创建新字符串,而只需返回 this
.
Although this is off-topic, but (as I said there almost
), it's worth knowing that, exception to this rule is when creating a substring
of same length, or any time a method returns the string with the same value, which will be optimized and will not create a new string, but simply return this
.
String s = "Rohit";
String s2 = s.substring(0, s.length());
System.out.println(s == s2); // will print true
这篇关于字符串修剪功能不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!