helpdesk helpdesk - 5 months ago 11
Java Question

Trim a string to remove white spaces

I have a string:

"hello world"
. This looks like it has no white space and so I tried to print it out the character
o
in the
hell
part of the string. I just did

string.chartAt(4)


but to my surprise, it printed out nothing.

I tried to debug it and realized that this string has over 20 leading white spaces. I could still print it out, now that I know where the leading white spaces end but my question is assuming one does NOT know where the white spaces end and one just want to trim the string so it can start printing from the first non-white space letter. How would one do this in Java? Apparently, using
string.trim()
didn't work.

Laf Laf
Answer

As stated in the Javadoc for String.trim():

Returns a copy of the string, with leading and trailing whitespace omitted.

The original String is not modified (Strings are immutable in Java). So you need to use the object returned after calling trim().

// Assuming you have stored the orginial String in a variable called 'myString'
myString = myString.trim ();
System.out.print (myString.charAt(4));

// or

System.out.print (myString.trim ().charAt(4));