Write a program that accepts an input string from the user and converts it into an array of words using an array of pointers. Each pointer in the array should point to the location of the first letter of each word. Implement this conversion in a function str_to_word which returns an integer reflecting the number of words in the original string. To help isolate each word in the sentence, convert the spaces to NULL characters. You can assume the input string has 1 space between each word and starts with an alphanumeric character. Your program’s input and output format should match the example run below. • You may only use stdio.h • Save your code as prob4.c.
Example Run
> This is a string.
4 word(s) found.
Please find the requested program below. Also including the screenshot of sample output and screenshot of code to understand the indentation.
Please provide your feedback
Thanks and Happy learning!
prob4.c:
#include <stdio.h>
int str_to_word(char inputStr[], const int arraySize)
{
char* wordList[100] = { NULL };
int wordCount = 0;
int wordStartPosition = 0;
int i = 0;
while (inputStr[i] != '\0' && i < arraySize)
{
if (inputStr[i] == ' ')
{
//Replace the space with '\0'(NULL) to indicate end of a word
inputStr[i] = '\0';
//This check is to avoid a single space been considered as a word
if (i != wordStartPosition)
{
//Point the char* in the wordList[] array to the start of the current word
wordList[wordCount] = inputStr + wordStartPosition;
//Increment the word count
++wordCount;
}
//set the next word start postition
wordStartPosition = i + 1;
}
++i;
}
//For the last word
if (inputStr[i] == '\0' && i != wordStartPosition)
{
wordList[wordCount] = inputStr + wordStartPosition;
++wordCount;
}
return wordCount;
}
int main()
{
const int arraySize = 100;
int wordCount = 0;
char inputStr[arraySize] = { '\0' };
printf("Enter a string: ");
gets_s(inputStr, 100);
//gets(inputStr);
wordCount = str_to_word(inputStr, arraySize);
printf("%d word(s) found.", wordCount);
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.