Count the number of white spaces in a Sentence

Problem statement:- Program to Count the number of white spaces in a Sentence.

Data requirement:-

   Input Data:- str

  Output Data:-count

  Additional Data:- i, len

Program in C

Here is the source code of the C Program to Count the number of white spaces in a Sentence.

Code:

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

Input/Output:
Enter your String:csinfo dot com
Number of white space in a string are :2

Program in C++

Here is the source code of the C++ Program to Count the number of white spaces in a Sentence.

Code:

#include<iostream>
using namespace std;
int main()
{
    string str;
    cout<<"Enter your String:";
    getline(cin,str);
    int i,count=0;
    int len=0;
    while(str[len]!='\0')
    {
        len++;
    }
    for(i=0;i<len;i++)
    {
    if(str[i]==' ')
    {
        count++;
    }
    }
    cout<<"Number of white space in a string are :"<<count;
}

Input/Output:
Enter your String:java c python c plus plus
Number of white space in a string are :6

Program in Java

Here is the source code of the Java Program to Count the number of white spaces in a Sentence.

Code:

import java.util.Scanner;
public class p18 {

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;
for(i=0;i<str.length;i++)
    {
    if(str[i]==' ')
    {
        count++;
    }
    }
System.out.println("Number of white space in a string are "+count);
cs.close();
}
}

Input/Output:
Enter your String:
java c 
Number of white space in a string are 2

Program in Python

Here is the source code of the Python Program to Count the number of white spaces in a Sentence.

Code:

str=input("Enter the String:")
count = 0
for i in range(len(str)):
    if str[i] == ' ':
        count+=1
print("Number of white space in a string are ",count)

Input/Output:

Enter the String:string problem python
Number of white space in a string are  2

Post a Comment

0 Comments