/** * @author lautturi.com * Java example: Java replace 2 or more spaces with one space in string */ import java.util.*; public class Lautturi { public static void main(String[] args) { String str = "hello java world!"; String newStr = str.trim().replaceAll(" +", " "); // Or // String newStr = str.trim().replaceAll("\\s+", " "); System.out.println(newStr); } }
output:
hello java world!