Count Number of Words in a String

Description

To count number of words in space separated string, loop through string and
count the spaces present in the string as each word always ends with a space.

Example : This is a cow.
          Number of words: 4

C/C++

/* C program to count total numbers words in a string */
//Save it as CountNumberOfWords.c

#include<stdio.h>
#include<string.h>

int main()
{
    char str[100];
    int i, length, countWords=0;

    printf("Enter a string : ");
    gets(str);

    printf("Entered String is : %s",str);

    length = strlen(str);

    if(length==0){
        printf("\nThe length of string is 0 as string is null");
    }else{
        for(i=0;i<length;i++){
            if(str[i]==' '){
                countWords++;
            }
        }
        printf("\nNo of words : %d",(countWords+1));
    }

    return 0;
}
Input:
Enter a string : 
This is a cow

Output:
Entered String is : This is a cow
No of words : 4

Java

/* Java program to count total numbers words in a string */
//Save it as CountNumberOfWords.java

import java.io.*;
import java.util.Scanner;
public class CountNumberOfWords {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a string : ");

        String str = scanner.nextLine();
        str = str.trim();
        
        System.out.println("Entered String is : "+str);
        
        if(str.length()==0) {
            System.out.println("The length of string is 0 as string is null");
        }else {
            String strArray[] = new String[100];
            
            strArray = str.split(" ");
            
            System.out.println("No of words : " + strArray.length);
        }
    }
}
Input:
Enter a string : 
This is a cow

Output:
Entered String is : This is a cow
No of words : 4

Related Programs

1) Find Occurrence Of Each Word In a Sentence
2) Print All Unique Words Of A String
3) Program To Print Unique Word Of A String Using Set
4) Program to Replace Spaces With Dots
5) Program to copy string
6) Program to Compare Two Strings
7) Program to Reverse a String
8) Find Substring of a Given String
9) Program to Insert a String into Another String
10) How to find Length or Size of a String
11) Program to sort characters of strings in alphabetical order
12) Program to Sort set of strings in alphabetical order
Share Me

Leave a Reply