Here you will get C++ program to count number of words in string.
First we initialize a counter variable to 1. Now iterate through string and count all the spaces, for each space increase the value of counter. Finally print the counter variable, it contains the number of words.
#include<iostream> #include<stdio.h> using namespace std; int main() { char a[100]; int i,count=1; cout<<"Enter a string:"; gets(a); for(i=0;a[i]!='\0';++i) { if(a[i]==' ') count++; } cout<<"\nThere are "<<count<<" words in the given string"; return 0; }
Output
Enter a string:how are you buddy?
There are 4 words in the given string
hey how do you do it using pointers
cool dude……………
one mistake- you should writ like this
if(a[i]!==' ')
{
count–;
}
I dont think there is any mistake in the logic that I have used in above program. You are telling wrong logic, please check it again.
wrong logic if i write- rohan,biswanath then
out put is 1;
one syntax error
for(i=0;a[i]!=’’;++i)
this should be like this
for(int i = 0; a[i] != ‘\0’; ++i)
I think there is one mistake. If we just use space then also it’s counting as word.
also if i give 2 or more spaces in between 2 words .the spaces will also be counted as words
Absolutely!
Try this…(for geany IDE)
===================
#include
using namespace std;
int main( )
{
char str[80];
int flag=0;
cout << "Enter a string: ";
cin.getline(str,80);
int words = 0;
for(int i = 0; str[i] != '\0'; i++)
{
if ((str[i] == ' '||str[i]==',')&&flag==0)
{
flag=1;
words++;
}
else if(str[i]!=' '&&str[i]!=',')
flag=0 ;
}
cout << "The number of words = " << words+1 << endl;
return 0;
}
I think this is not a true program for counting the no. of words in a string.
The reason behind is that, if we give a space or more spaces after the string ends, it gives wrong answer.
This logic won’t work if there are multiple gaps(spaces) between two words.
For example( cat and. Dog. T) the program show’s the number of words as more than 4.
Actually you can make the change easily
Instead of (if a[I]==’ ‘)
{ Count++;}
Write the code as
For(a[i]==’ ‘&&a[i+1]!= ‘ ‘)
{
Count++
}
It will be great if you add
if(a[0]==’ ‘)
–count;
after the for loop.
This will help for this type of sentences
” A bird can fly”
Help ! HELP !
//WAP to count no.of lines that begin with’ A’
I am not getting the desired output with this input.It is giving 1 as the no. of words in every string irrespective of its length.Kindly help!!!
Or you guys can do this
Take braces as parentheses
for{i=0 ; a[i]!=’/0′ ; i++}
{
if{{a[i]==’ ‘ || a[i]==’,’} && a[i+1]!=’ ‘}
words++;
}
You guys for got to do a conditional on the loop, Other wise; it wont see a ‘solo’ word..
for ( int i = 0; i < 0; i++) // no code – unless you want to see it 'n' times
{
if (user_input[i] == ' ' || user_input[i-1] == '