I need to count the number of spaces in my string but my code gives me a wrong number when i run it, what is wrong?
int count=0;
String arr[]=s.split("\t");
OOPHelper.println("Number of spaces are: "+arr.length);
count++;
解决方案
s.length() - s.replaceAll(" ", "").length() returns you number of spaces.
There are more ways. For example"
int spaceCount = 0;
for (char c : str.toCharArray()) {
if (c == ' ') {
spaceCount++;
}
}
etc., etc.
In your case you tried to split string using \t - TAB. You will get right result if you use " " instead. Using \s may be confusing since it matches all whitepsaces - regular spaces and TABs.