Count Number of Words in a String
“Count Number of Words in a String” is a basic problem of string data structure. Here, we are given string containing some words and our task is to write a program to count the number of words present in the given string and print the count.
Example:
INPUT: Help Me Study Bro OUTPUT: 4 INPUT: Helpmestudybro is an emerging website. OUTPUT: 5
The steps required to Count Number of Words in a String is as follows:
- Scan the complete string.
- While scanning, keep count of every blank spaces encountered.(Each word of the string will be separated by blank space, obviously).
- The result will the count + 1.
C++ Program to Count Number of Words in a String is as follows:
/* Program to Count Number of Words in a String */
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str;
cout<<"Enter a string:\n";
getline(cin,str);
int size = str.length();
int count = 0;
for(int i = 0; i < size; i++)
{
if(str[i] == ' ')
count++;
}
cout<<"Total number of words in the string are: "<<count+1;
}
OUTPUT: Enter a string: HelpMeStudyBro is an emerging website Total number of words in the string are: 5 Time Complexity: O(n), where n is the length of the string
Related Posts:
- Program to find smallest and largest word of the String.
- Program to find Most Frequent Character of the String.
- Program to Remove all the blank spaces from the String.
- Program to check if String is isogram or not.
- Program to Reverse Each word of the String.
- Program to Print All the Substring of the Given String.
- Program to find longest palindromic Substring.
- Program to check Anagram Strings.
- Program to check whether two Strings are Rotation of each other or not.
- Program to check Palindromic Anagram.
- Program to print all the Palindromic Substring of the String.
- Program to check Panagram String.
- Program to find first non-repeating character of the String.
- Merge Overlapping Intervals using Stacks
- Implement Stack Using Linked List
- Largest Rectangular Area in Histogram
- Length of Longest Valid Substring
- Reverse a String using Stack
- Implement two stacks in a single array
- Program to print kth smallest and kth largest element of an Array.