Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions count-word-in-sentence.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/* C++ program to count no of words
from given input string. */
#include <bits/stdc++.h>
using namespace std;

#define OUT 0
#define IN 1

// returns number of words in str
unsigned countWords(char *str)
{
int state = OUT;
unsigned wc = 0; // word count

// Scan all characters one by one
while (*str)
{
// If next character is a separator, set the
// state as OUT
if (*str == ' ' || *str == '\n' || *str == '\t')
state = OUT;

// If next character is not a word separator and
// state is OUT, then set the state as IN and
// increment word count
else if (state == OUT)
{
state = IN;
++wc;
}

// Move to next character
++str;
}

return wc;
}

// Driver code
int main(void)
{
char str[] = "One two three\n four\tfive ";
cout<<"No of words : "<<countWords(str);
return 0;
}

// This is code is contributed by rathbhupendra