Showing posts with label whitespace. Show all posts
Showing posts with label whitespace. Show all posts

Monday, June 11, 2012

String trim()

DOWNLOAD THE CODE: TrimmingWhitespace

The Java Character class defines whitespace as one of a few different types of characters, including the space character & a carriage return character.

The String class contains a trim() function which removes leading & trailing (at the beginning and at the end) whitespace.

For example, if we are reading a text file using Scanner, with a semi-colon as the delimiter, we only want to read the meaningful part of the string. Carriage returns should be discarded.

For our examples, we will use the following text file nums.txt. See screenshot below:



The code example below reads nums.txt, inside of a while loop.The semi-colon is used as the Scanner's delimiter. Each token in the string ends with a semi-colon and the next begins immediately after the semi-colon. This means that any carriage return characters may be included in the token. This is not ideal and will produce the following result:


Here is the output:


Note that the carriage return separating the lines between the tokens "five" and "six" has been read and rendered.

Using trim()
In the example below, we will trim() each token so that any whitespace such as carriage return characters are discarded.


Here is the output: