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

I have the string "22" and I get 3 as the length;

I used .trim()

What else could be causing this?

+7
java string
source share
3 answers

You should give us code that demonstrates the problem, but I think you did something like this:

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

But str.trim() does not change str (since strings are immutable). Instead, it returns a new string trim. So you need something like this:

 String str = "22 "; str = str.trim(); System.out.println(str.length()); 
+27
source share

Try the following:

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

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

+11
source share

since I found the reason when formulating the question, I am going to answer myself.

If a string was created .substring or split, the entire string is saved plus the position and length of the substring.

it is apparently impossible to trim (was "22")

-2
source share

All Articles