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++;
To count the spaces in a string:Use the split() method to split the string on each space. Access the length property on the array and subtract 1. The result will be the number of spaces in the string.
Java String length method() The Java String class contains a length() method that returns the total number of characters a given String contains. This value includes all blanks, spaces, and other special characters. Every character in the String is counted.
In order to check if a String has only unicode digits or space in Java, we use the isDigit() method and the charAt() method with decision making statements. The isDigit(int codePoint) method determines whether the specific character (Unicode codePoint) is a digit. It returns a boolean value, either true or false.
Manual SpacingSystem. out. println(i + " " + j + " " + k);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With