Java Strings: White Space
trim() Method
The trim() method removes white space from beginning and end of a given string. This is very useful when handling data from external sources like a user input field where a user could unknowingly add spaces before or after a string. Have you ever copied and pasted your username or password into a website login page only to find it doesn’t work? In those situations it is likely that you have unknowingly included a space when you copied the data. In that case, since Java considers spaces as characters, the startIndex of that string would not refer to a visible character and it would make working with the charAt() methods difficult.
So, now that we know what it does and why it’s a good thing, let see it in action:
//Create a string with a space before and after String spaceyString = " Learning Glue "; //Returns the value of spaceyString System.out.println("The untrimmed string is: " + spaceyString); System.out.println("The untrimmed string is: " + spaceyString.length() + " characters long."); spaceyString = spaceyString.trim(); System.out.println("The untrimmed string is: " + spaceyString); System.out.println("The untrimmed string is: " + spaceyString.length() + " characters long.");
The output returns both the untrimmed and trimmed string and the number of character in each:
run: The untrimmed string is: Learning Glue The untrimmed string is: 15 characters long. The trimmed string is: Learning Glue The trimmed string is: 13 characters long. BUILD SUCCESSFUL (total time: 0 seconds)