Remove extra spaces from string in java

This is a code to remove extra spaces from string.
String str = “i  am     reading    this book  since yesterday.”;

String s1 = “”;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ' && str.charAt(i + 1) == ' ') {
str = str.substring(0, i).concat(
str.substring(i + 1, str.length()));
i–;

}

}
System.out.println("string without space :"+str);

Posted from WordPress for Android

Advertisements