user3044679
user3044679

Reputation: 1

Trimming spaces while still keeping words

I have a data file that contains String inputs like the following:

Tour    g
tour i
stall    2
 venue 2

and I need to trim the spaces down for proper comparison:

for(int l=0; l<listOfFacilities.size(); l++)
{

   String tempFacName = listOfFacilities.get(l).getFacilityName(); //string to be compared to
   if(tempFacName.contains(facility.toLowerCase() )==true) //facility is the string from above taken from an imput file
        System.out.println("true");

}

but I was wondering if there was any way to trim the spaces before, after, and inbetween but still retain one space in the middle. to turn ( venue 2 ) into (venue 2)? I understand how to use .replace() and .replaceAll() to trim all the spaces down, however I want to avoid turning all my strings into (venue2), (tourg), etc. any help is greatly appreciated

Upvotes: 0

Views: 52

Answers (1)

Blub
Blub

Reputation: 3822

Maybe try like this:

tempFacName = tempFacName.replaceAll("\\s+", " ").trim();

This replaces every whitespace with a space and then removes spaces from the beginning and the end of the String.

See also the javadoc for String.trim()

Upvotes: 2

Related Questions