public class RemoveDuplicateWhiteSpaces {
public static void main(String[] args) {
String str = " Java is a simple language ";
StringBuffer buff = new StringBuffer();
String correctedString = "";
boolean space = false;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == ' ') {
if (!space && i > 0) {
buff.append(c);
}
space = true;
}
else {
buff.append(c);
space = false;
}
}
String temp = buff.toString();
if (temp.charAt(temp.length() - 1) == ' ') {
correctedString = temp.substring(0, buff.toString().length() - 1);
System.out.println(str);
System.out.println(correctedString);
}
}
}
Output:
Java is a simple language
Java is a simple language
No comments:
Post a Comment