Complementary task for topic: 7
M Nemeth · 2023-08-29 15:21:04.624218'
DStrings: Count Words in a Dynamic String
DStrings: Count Words in a Dynamic String
Create a C program that reads a dynamic string from the user and counts the number of words in it. A word is defined as a sequence of non-space characters separated by one or more spaces.
Hint: Use dynamic memory allocation to create the string.
Prompt the user to enter a dynamic string.
Count the number of words in the string.
Display the original string and the word count as output.
Deallocate the memory used by the dynamic string.
Solution
#include
#include
#include
int countWords(char* str) {
int count = 0;
int isWord = 0;
while (*str != '\0') {
if (!isspace(*str)) {
if (!isWord) {
isWord = 1;
count++;
}
} else {
isWord = 0;
}
str++;
}
return count;
}
int main() {
char* dynamicString = NULL;
printf("Enter a string: ");
scanf("%m[^\n]", &dynamicString);
int wordCount = countWords(dynamicString);
printf("Original string: %s\n", dynamicString);
printf("Number of words: %d\n", wordCount);
// Deallocate the memory used by the dynamic string
free(dynamicString);
return 0;
}
Explanation
The program defines a function countWords() that takes a dynamic string as an argument and returns the number of words in the string. In the countWords() function, we use a while loop to iterate through the string character by character. We maintain a variable isWord to keep track of whether we are inside a word or not. If the current character is not a space (as determined by isspace() from ctype.h), we check if we are starting a new word. If so, we increment the count variable and set isWord to 1. If the current character is a space, we set isWord to 0, indicating that we are no longer inside a word. The countWords() function returns the final count of words. In the main function, the user is prompted to enter a dynamic string using scanf("%m[^\n]", &dynamicString), which dynamically allocates memory for the input string. The main function then calls the countWords() function to determine the word count. The original string and the word count are displayed using printf(). Finally, the memory used by the dynamic string is deallocated using free() to avoid memory leaks.