Dang Tuan Hung
Dang Tuan Hung

Reputation: 11

How to remove duplicated white spaces in a string and count the number of removed spaces in Java?

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

Answers (4)

Thomas Jungblut
Thomas Jungblut

Reputation: 20969

Why not?

 String s = "     ";
 String whiteSpaceLess = s.replaceAll("  ", "");
 int diff = s.length() - whiteSpaceLess.length();

Upvotes: 1

blueygh2
blueygh2

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

fge
fge

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

nrubin29
nrubin29

Reputation: 1612

Before you replaceAll() you could iterate over all characters with stringVar.toCharArray() and count.

Upvotes: 1

Related Questions