Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: getting incorrect string.length() after using trim()

Tags:

java

string

I have the string "22" and I'm getting 3 as length;

I used .trim()

What else could be a reason for this?

like image 508
Jan Avatar asked May 30 '10 16:05

Jan


People also ask

What does trim () does in Java?

Java String trim() Method The trim() method removes whitespace from both ends of a string.

How do I cut a string to a specific length?

Using String's substring() Method. The String class comes with a handy method called substring. As the name indicates, substring() returns the portion of a given String between the specified indexes. In the above example, if the specified length is greater than the length of text, we return text itself.

Can string length be changed Java?

String are immutable in Java. You can't change them. You will need to use another String or use StringBuilder.


2 Answers

You should be giving us code that demonstrates the problem, but my guess is you did something like this:

String str = "22 ";
str.trim();
System.out.println(str.length());

But str.trim() doesn't change str (as Strings are immutable). Instead it returns a new String trimmed. So you need something like this:

String str = "22 ";
str = str.trim();
System.out.println(str.length());
like image 75
Mark Peters Avatar answered Sep 24 '22 18:09

Mark Peters


Try this:

System.out.println(java.util.Arrays.toString(theString.toCharArray()));

This dumps the char[] version of the String, so we can perhaps see if it contains anything funny.

like image 30
polygenelubricants Avatar answered Sep 26 '22 18:09

polygenelubricants