Program to count the total number of words in a string.

Here, we have a basic program example to count the number of words in a string using different languages. This program is created in c language, c++, Java, and Python.

Code to count the word in a string in C language

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define str_size 100

void main()
{
    char str[str_size];
    int i, word;
       printf("Input the string : ");
       fgets(str, sizeof str, stdin);
       i = 0;
       word = 1;
    while(str[i]!='\0')
    {
        if(str[i]==' ' || str[i]=='\n' || str[i]=='\t')
        {
            word++;
        }
        i++;
    }
    printf("Total number of words in the string is : %d\n", word-1);
}

Code to count the word in a string in C++ language

#include<iostream>
using namespace std;
int main( )
{
	char str[80];
	cout << "Enter a string: ";
	cin.getline(str,80);
	int words = 0; // Holds number of words
	for(int i = 0; str[i] != '\0'; i++)
	{
		if (str[i] == ' ') //Checking for spaces
		{
			words++;
		}
	}
	cout << "The number of words = " << words+1 << endl;
	return 0;
}

Code to count the word in a string in Python language

count_str = input("Input a string: ")
word = len(count_str.split())
print ("The number of words in string are : " + str(word))

Code to count the word in a string in Java language

import java.util.Scanner;
public class wordCount {
  public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Input the string: ");
        String str = in.nextLine();
        System.out.print("Number of words in the string: " + count_Words(str)+"\n");
    }
 public static int count_Words(String str)
    {
       int count = 0;
        if (!(" ".equals(str.substring(0, 1))) || !(" ".equals(str.substring(str.length() - 1))))
        {
            for (int i = 0; i < str.length(); i++)
            {
                if (str.charAt(i) == ' ')
                {
                    count++;
                }
            }
            count = count + 1;
        }
        return count;
    }
 }