This forum has a solution for removing duplicated white spaces in java using
String.replaceAll()
However this solution can't be applied if we need to count the removed white spaces. Is there any other way to solve this problem?
This forum has a solution for removing duplicated white spaces in java using
String.replaceAll()
However this solution can't be applied if we need to count the removed white spaces. Is there any other way to solve this problem?
Before you replaceAll()
you could iterate over all characters with stringVar.toCharArray()
and count.
Why not?
String s = " ";
String whiteSpaceLess = s.replaceAll(" ", "");
int diff = s.length() - whiteSpaceLess.length();
Simply retain the original string in another variable. After trimming it from extra spaces, just calculate the length difference: this is the number of spaces removed.
If you have a String s,
String t = s.replaceAll("\\s+", " ");
System.out.println(t);
int count = s.length() - t.length();
System.out.println(count);
You can remove the whitespaces using replaceAll, and count the difference in length between the strings to get the number of removed spaces.