Reputation: 11
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?
Upvotes: 0
Views: 388
Reputation: 20969
Why not?
String s = " ";
String whiteSpaceLess = s.replaceAll(" ", "");
int diff = s.length() - whiteSpaceLess.length();
Upvotes: 1
Reputation: 1538
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.
Upvotes: 1
Reputation: 121860
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.
Upvotes: 1
Reputation: 1612
Before you replaceAll()
you could iterate over all characters with stringVar.toCharArray()
and count.
Upvotes: 1