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++;
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++;
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.
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();
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.
\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, " " );
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.
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
.
Another way using regular expressions
int length = text.replaceAll("[^ ]", "").length();
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);
}
}
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++;
}
}
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;
}
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);
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);
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);
}
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);
}
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);
}
}
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);
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);
}
}