2. You are to write a subroutine/function which will expect a string as input. T
ID: 3588562 • Letter: 2
Question
2. You are to write a subroutine/function which will expect a string as input. The function shouid count the total number of words in the string calculated as the number of blocks of space characters plus one. The subroutine should then return this quantity as an integer. Two or more consecutive space characters should only count as one block. Example: The string "Bob has twelve apples." should report 4 words because it contains three space characters. Note that the ASCII code for space is 0x20 Example: The string "Bob has twelve contains three blocks of space characters. apples."should also report 4 words because inExplanation / Answer
#include <stdio.h>
/* Function to Count the number of words in a string by traversing through each character*/
int countWordsInString(char *string)
{
int state = 0;
int wordCount = 0; // Initialize the word count to zero
/* Scan each character in the string one by one*/
while (*string)
{
/* If next character is a space, set the State as 0 */
if (*string == ' '){
state = 0;
}
/* If next character is not a space and state is 0, then set the state as 1 and increment the word count */
else if (state == 0)
{
state = 1;
++wordCount;
}
++string;
}
return wordCount;
}
int main(void)
{
/*Enter the String Here you want to test */
char string[] = "Enter your String Here";
printf("No of words in the given Input String : %d", countWordsInString(string));
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.