Count the number of words in a string in C++
In this tutorial, we will learn how to count the number of words in a string in C++. There can be various ways to do this. The following is a simple one. Given a string, words can be separated by the following characters:
- Space-” “
- New line-“\n”
- Tab-“\t”
- Or a combination of these.
How to count the number of words in a string in C++
For example-
String=”An apple\ta \nday keeps a\ndoctor \naway \t ”
The number of words here are:7
String=”apple pear tomato\n\t yoaster ”
The number of words here are:5
Algorithm:
- We will check each character one by one.
- A word will be there only and only if its previous character is whitespace and the current character is an alphabet.
- By keeping this logic in mind, we can store current and previous char and pass them in a function isword().
- The isword() function will return true if the previous character is whitespace and the current one an alphabet.
bool isAlpha(char c){ return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); } bool isWhiteSpace(char c){ return c == ' ' || c == '\n' || c == '\t'; }
These function will check if the character is an alphabet or whitespace.
Here is the code implementation:
#include <bits/stdc++.h> using namespace std; bool isAlpha(char c){ return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); } bool isWhiteSpace(char c){ return c == ' ' || c == '\n' || c == '\t'; } bool isWord(char cur, char previous){ return isAlpha(cur) && isWhiteSpace(previous); } int countWords(char *str) { int count=0; char cur; char previous = ' '; while (*str) { cur=*str; if (isWord(cur, previous)) count++; previous = cur; // Move to next character ++str; } return count; } int main() { char str[] = "apple pear tomato\n\t yoaster "; cout<<"No of words : "<<countWords(str); return 0; }
Output:
No of words:4
Input: ” Hello from the other side”
Output:
No of words:5
Time complexity is o(n)
Also, refer to:
Create all possible strings from a given set of characters in C++
Leave a Reply