Here we can obtain two ways to remove multiple spaces in a string in Java. The first way is to replace multiple spaces with the replaceAll() method in the string object.The second way is to wrap the string into a StringTokenizer object using the nextToken(” “) method.
Source Code
1)
package com.beginner.examples;
public class RemoveExtraWhitespace1 {
public static void main(String[] args) {
//This is a string that needs to be processed
String str = "I love java";
//Use regular to replace multiple Spaces with one
str = str.replaceAll(" +", " ");
System.out.println(str);
}
}
Output:
I love java
2)
package com.beginner.examples;
import java.util.StringTokenizer;
public class RemoveExtraWhitespace2 {
public static void main(String[] args) {
//This is a string that needs to be processed
String testStr = "This is a string that needs to be processed";
//Encapsulate this string into a StringTokenizer object
StringTokenizer st = new StringTokenizer(testStr);
//Store separated strings
StringBuilder sb = new StringBuilder();
while(st.hasMoreElements()) {
String word =st.nextToken(" ");
sb.append(word).append(" ");
}
System.out.println(sb.toString());
}
}
Output:
This is a string that needs to be processed
References
Imported packages in Java documentation: