forked from MainakRepositor/500-CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
178.cpp
47 lines (38 loc) · 816 Bytes
/
178.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/* 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;
}