Superfluous white space


Java provides ways of removing superfluous white space from within a string. This white space can either be multiple embedded spaces or leading/trailing spaces.

Imagine that we start off with our strings.

String s1 = "     the          quick        brown fox jumps over        the    lazy dog    ";
 String s2 = "";
 System.out.format ("The original string = <%s>%n", s1);

I’ve used the angle brackets to show the outer limits of the string when printed to the screen.

Trimming the string

To trim the string, we’ll use the trim() method from the String class. As the documentation says, this:

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

So to do this,

System.out.println("Removing leading and trailing spaces");
 s2 = s1.trim();
 System.out.format ("(leading/trailing spaces removed) s2 = <%s>%n", s2);

It will be seen from the angle brackets that the string has indeed been trimmed.

Removing embedded spaces

To remove the embedded spaces, we can use the replaceAll(String regex, String replacement) method from the String class. Multiple spaces will be replaced by one space within the string.

System.out.println("Removing embedded spaces");
 s2 = s2.replaceAll(" {2,}", " ");
 System.out.format ("(embedded spaces removed) s2 = <%s>%n", s2);
 System.out.format ("s2 = <%s>%n", s2);

The replaceAll method:

Replaces each substring of this string that matches the given regular expression with the given replacement.

See also

The API documentation for the Class java.lang.String.

This entry was posted in java and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s