Java Program to Count Number of Words and Spaces in a String

This is the java program to count number of words and spaces in a string. I have taken initial value of word as 1 because if there is only one word in the string then there will be no space. The total spaces will be one less than the total number of words. It is a simple program and self explanatory, still if you are facing any problem to understand this then comment below. 

class StringDemo
{
 public static void main(String...s)
 {
  int word=1;
  String str="count number of words and sapces";

  for(int i=0;i<str.length();++i)
  {
   if(str.charAt(i)==' ')
    word++;
  }

  System.out.println("Number of words="+word);
  System.out.println("Number of spaces="+(word-1));
 }
}

Output

Java Program to Count Number of Words and Spaces in a String

14 thoughts on “Java Program to Count Number of Words and Spaces in a String”

  1. your countword program wrong because when we pass
    String str=” count number of words and sapces “;
    space in a starting then it gives wrong value

    1. Abhijeet Dahale

      two separate logic for counting space and words would do it, for handling “space at beginning or at end or at any place in the string gives wrong output”

      int count = 0;
      int words = 0;
      for (int i = 0; i < s.length(); ++i) {
      if (s.charAt(i) == ' ')
      count++;
      }
      System.out.println("Number of spaces=" + count);

      for (int i = 0; i < s.length() – 1; i++) {
      if ((s.charAt(i) == ' ') && (s.charAt(i + 1) != ' '))
      words++;
      }
      System.out.println("Number of words in a string = " + words);

  2. class Test
    {
    public static void main(String…s)
    {
    int word=1;
    String str=”count number of words and sapces”;
    String[] str1=str.split(” “);
    System.out.println(“Number of words=”+str1.length);
    System.out.println(“Number of spaces=”+(str1.length – 1));
    }
    }

    1. Debangshu Acharyya

      but the word counter when you are initializing as one so if the user enters nothing then also the count will show that the number of words are one

  3. public class CountWordsInString

    {
    public static void main(String…s)
    {
    int word=0;
    String str=” count number of words and sapces “;
    char ch[]= new char[str.length()];
    for(int i=0;i0)&&(ch[i]!=’ ‘)&&(ch[i-1]==’ ‘)) || ((ch[0]!=’ ‘)&&(i==0)) )
    word++;
    }

    System.out.println(“Number of words=”+word);
    //System.out.println(“Number of spaces=”+(word-1));
    }
    }

Leave a Comment

Your email address will not be published. Required fields are marked *