Example
String str = " texto com espaços em branco ";
Result
"text with spaces"
Example
String str = " texto com espaços em branco ";
Result
"text with spaces"
You can use a regular expression:
System.out.println(" texto com espaços em branco".replaceAll("\s+", " "));
Result
Text with blanks
To also remove spaces at the ends, you can first apply the trim () function:
System.out.println(" texto com espaços em branco".trim().replaceAll("\s+", " "));
The idea is that the regular expression \s
matches any white space character.
If any pattern is followed by a +, it means that this pattern needs to appear 1 or more times. In this case, \ s +, matches with one or more consecutive blanks.
This information is then passed to the ReplaceAll function that replaces the consecutive spaces found, with only one blank space.
You can use the Scanner class
Scanner s = new Scanner(text);
String t = null;
while (s.hasNext()) {
if(t == null)
t = s.next();
else
t = t +" "+s.next();
}
System.out.println(t);