How to replace multiple spaces with single space in Java
To replace the multiple white spaces from a string with a single white space, we can use the replaceAll()
method by passing the //s+
regex as a first argument and single space (" "
) as the second argument.
Here is an example:
public class Main
{
public static void main(String[] args) {
String name= "John doe ray"; String removeSpaces = name.replaceAll("\\s+", " "); System.out.println(removeSpaces);
}
}
Output:
"John doe ray"