I have the string "22"
and I'm getting 3 as length;
I used .trim()
What else could be a reason for this?
Java String trim() Method The trim() method removes whitespace from both ends of a string.
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.
String are immutable in Java. You can't change them. You will need to use another String or use StringBuilder.
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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With