Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count the spaces in a java string?

Tags:

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++; 
like image 415
kamweshi Avatar asked Mar 11 '12 14:03

kamweshi


People also ask

How do you count the number of spaces in a string?

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.

Are spaces counted in string length Java?

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.

How do I check if a string contains spaces?

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.

How do you show spaces in Java?

Manual SpacingSystem. out. println(i + " " + j + " " + k);


1 Answers

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.

like image 181
AlexR Avatar answered Oct 07 '22 16:10

AlexR