Reputation: 385
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");
println("Number of spaces are: "+arr.length);
count++;
Upvotes: 26
Views: 152292
Reputation: 115328
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++;
}
}
In your case you tried to split the string using \t
, i.e. TAB. You will get the right result if you use " "
instead. Using \s
may be confusing since it matches all whitespaces, i.e. regular spaces and TABs.
Upvotes: 39
Reputation: 93
import java.util.Scanner;
import java.io.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in).useDelimiter("\n");
String str = sc.next();
int spaceCount=0;
str = str.toLowerCase();
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i)==' '){
spaceCount++;
}
}
System.out.println("Number of spaces: "+ spaceCount);
}
}
Upvotes: 0
Reputation: 424983
Here is a different way of looking at it, and it's a simple one-liner:
int spaces = s.replaceAll("[^ ]", "").length();
This works by effectively removing all non-spaces then taking the length of what’s left (the spaces).
You might want to add a null check:
int spaces = s == null ? 0 : s.replaceAll("[^ ]", "").length();
You can use a stream too:
long spaces = s.chars().filter(c -> c == (int)' ').count();
Upvotes: 25
Reputation: 6686
If you use Java 8, the following should work:
long count = "0 1 2 3 4.".chars().filter(Character::isWhitespace).count();
This will also work in Java 8 using Eclipse Collections:
int count = Strings.asChars("0 1 2 3 4.").count(Character::isWhitespace);
Note: I am a committer for Eclipse Collections.
Upvotes: 4
Reputation: 1384
The simple and fastest way to count spaces
String fav="foo hello me hi";
for( int i=0; i<fav.length(); i++ ) {
if(fav.charAt(i) == ' ' ) {
counter++;
}
}
Upvotes: 1
Reputation: 2958
The most precise and exact plus fastest way to that is :
String Name="Infinity War is a good movie";
int count =0;
for(int i=0;i<Name.length();i++){
if(Character.isWhitespace(Name.charAt(i))){
count+=1;
}
}
System.out.println(count);
Upvotes: 0
Reputation: 103
please check the following code, it can help
public class CountSpace {
public static void main(String[] args) {
String word = "S N PRASAD RAO";
String data[];int k=0;
data=word.split("");
for(int i=0;i<data.length;i++){
if(data[i].equals(" ")){
k++;
}
}
System.out.println(k);
}
}
Upvotes: 1
Reputation: 1
This program will definitely help you.
class SpaceCount
{
public static int spaceCount(String s)
{ int a=0;
char ch[]= new char[s.length()];
for(int i = 0; i < s.length(); i++)
{ ch[i]= s.charAt(i);
if( ch[i]==' ' )
a++;
}
return a;
}
public static void main(String... s)
{
int m = spaceCount("Hello I am a Java Developer");
System.out.println("The number of words in the String are : "+m);
}
}
Upvotes: 0
Reputation: 1
public static void main(String[] args) {
Scanner input= new Scanner(System.in);`
String data=input.nextLine();
int cnt=0;
System.out.println(data);
for(int i=0;i<data.length()-1;i++)
{if(data.charAt(i)==' ')
{
cnt++;
}
}
System.out.println("Total number of Spaces in a given String are " +cnt);
}
Upvotes: 0
Reputation: 1
public static void main(String[] args) {
String str = "Honey dfd tEch Solution";
String[] arr = str.split(" ");
System.out.println(arr.length);
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (!arr[i].trim().isEmpty()) {
System.out.println(arr[i]);
count++;
}
}
System.out.println(count);
}
Upvotes: 0
Reputation: 15703
I just had to do something similar to this and this is what I used:
String string = stringValue;
String[] stringArray = string.split("\\s+");
int length = stringArray.length;
System.out.println("The number of parts is: " + length);
Upvotes: 0
Reputation: 12367
Fastest way to do this would be:
int count = 0;
for(int i = 0; i < str.length(); i++) {
if(Character.isWhitespace(str.charAt(i))) count++;
}
This would catch all characters that are considered whitespace.
Regex solutions require compiling regex and excecuting it - with a lot of overhead. Getting character array requires allocation. Iterating over byte array would be faster, but only if you are sure that your characters are ASCII.
Upvotes: 8
Reputation: 36703
A solution using java.util.regex.Pattern / java.util.regex.Matcher
String test = "foo bar baz ";
Pattern pattern = Pattern.compile(" ");
Matcher matcher = pattern.matcher(test);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println(count);
Upvotes: 1
Reputation: 533492
Another way using regular expressions
int length = text.replaceAll("[^ ]", "").length();
Upvotes: 2
Reputation: 9256
\t
will match tabs, rather than spaces and should also be referred to with a double slash: \\t
. You could call s.split( " " )
but that wouldn't count consecutive spaces. By that I mean...
String bar = " ba jfjf jjj j ";
String[] split = bar.split( " " );
System.out.println( split.length ); // Returns 5
So, despite the fact there are seven space characters, there are only five blocks of space. It depends which you're trying to count, I guess.
Commons Lang is your friend for this one.
int count = StringUtils.countMatches( inputString, " " );
Upvotes: 5
Reputation:
The code you provided would print the number of tabs, not the number of spaces. The below function should count the number of whitespace characters in a given string.
int countSpaces(String string) {
int spaces = 0;
for(int i = 0; i < string.length(); i++) {
spaces += (Character.isWhitespace(string.charAt(i))) ? 1 : 0;
}
return spaces;
}
Upvotes: 1
Reputation: 3450
Your code will count the number of tabs and not the number of spaces. Also, the number of tabs will be one less than arr.length
.
Upvotes: 2