3. Word Counter Write a function that accepts a pointer to a C-string as an argu
ID: 3669919 • Letter: 3
Question
3. Word Counter
Write a function that accepts a pointer to a C-string as an argument and returns the
number of words contained in the string. For instance, if the string argument is “Four
score and seven years ago” the function should return the number 6. Demonstrate the
function in a program that asks the user to input a string and then passes it to the function.
The number of words in the string should be displayed on the screen. Optional
Exercise: Write an overloaded version of this function that accepts a string class object
as its argument.
c++
Explanation / Answer
//hi!!
// code starts from here... use any C compiler or C++ microsoft complier.
#include <stdio.h> // main library function for input and output
extern unsigned countWords(char *str); // extern:storage type globally defined this function to call anywhere
int main(void)
{
char str[] = " American sniper 007 "; //type your string here
printf(" User typed words: %s ", str );
printf(" Number of words contained in the string: %u ", countWords(str));
return 0;
}
#define OUT 0 // the preprocessor command used for count the words in Character input
#define IN 1 // the preprocessor command used for count the words
// 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 == ' ' || *str == ' ')
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;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.