Count number of the words in a String

Problem statement:- Program to Count the number of words in a String.

Data requirement:-

   Input Data:- str

  Output Data:- count

  Additional Data:- i, flag

Program in C

Here is the source code of the C Program to Count the number of words in a String.

Code:

#include<stdio.h>
#include<string.h>
int main()
{
    char str[30];
    printf("Enter your String:");
    scanf("%[^\n]",str);
    int i,count=0,flag=0;
    for(i=0;i<strlen(str);i++)
    {
    if(str[i]==' ' || str[i]=='\t' || str[i]=='\n')
        flag=0;
    else if(flag==0)
    {
        flag=1;
        ++count;
    }
    }
    printf("Word present in a string are %d",count);
}

Input/Output:
Enter your String:csinfo dot
Word present in a string are 2

Program in C++

Here is the source code of the C++ Program to Count the number of words in a String.

Code:

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
    string str;
    cout<<"Enter your String:";
    getline(cin,str);
    int len=0;
    while(str[len]!='\0')
    {
        len++;
    }
    int i,count=0,flag=0;
    for(i=0;i<len;i++)
    {
    if(str[i]==' ' || str[i]=='\t' || str[i]=='\n')
        flag=0;
    else if(flag==0)
    {
        flag=1;
        ++count;
    }
    }
    cout<<"Word present in a string are "<<count;
}

Input/Output:
Enter your String:csinfo dot 360
Word present in a string are 3

Program in Java

Here is the source code of the Java Program to Count the number of words in a String.

Code:

import java.util.Scanner;
public class p17 {

public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
String str1;
System.out.println("Enter your String:");
str1=cs.nextLine();
char[] str=str1.toCharArray();
int i,count=0,flag=0;
for(i=0;i<str.length;i++)
    {
    if(str[i]==' ' || str[i]=='\t' || str[i]=='\n')
        flag=0;
    else if(flag==0)
    {
        flag=1;
        ++count;
    }
    }
System.out.println("Word present in a string are "+count);

cs.close();
}

}

Input/Output:
Enter your String:
string program in java
Word present in a string are 4

Program in Python

Here is the source code of the Python Program to Count the number of words in a String.

Code:
str1=input("Enter the String:")
str2=len(str1.split())
print("Word present in a string are ",str(str2))

Input/Output:
Enter the String: java program problem
Word present in a string are  3

Post a Comment

0 Comments