Reputation: 13
Lets say I have a string with some text:
String str="Hello My Name Is Help!"
And I want to check how much space chars I have in the following String str
. I would like a make a method that takes that following string and returns the number of whitespaces
in that string. For example if I name my method getNumberOfWhiteSpaces(String str)
and call it a I should get back the number of whitespaces.
if( getNumberOfWhiteSpaces(String str) > 3)
System.out.println("There are more then 3 spaces in this string");
public int getNumberOfWhiteSpaces(String str) {
....
return some number
}
Upvotes: 0
Views: 152
Reputation: 36431
Java 8 way could be:
s.chars().filter(Character::isWhitespace).count()
which will give you the number of white space in the string s
. You can also use isSpaceChar
.
Upvotes: 1
Reputation: 4282
Try:
String str="Hello My Name Is Help!";
int spaces = str.length() - str.replace(" ", "").length();
if(spaces > 3){
System.out.println("There are more then 3 spaces in this string");
}
Upvotes: 1
Reputation: 60046
A solution is to use replaceAll
to replace all non space ([^\s]
) with empty and check the length of result output :
if (str.replaceAll("[^\\s]", "").length() > 3) {...}
Upvotes: 1