C Code - Using Character Functions Skeleton Code: Test Caes: http://www.comp.nus
ID: 3601730 • Letter: C
Question
C Code - Using Character Functions
Skeleton Code:
Test Caes: http://www.comp.nus.edu.sg/~cs1010/practice/2017s1/Practice-S08P02/testdata/
Practice S08P02: Count Number of Words Week of release: Week 9 Objective: Using character functions Task statement: Write a program countWords.c to read an English sentence and count the number of words in the sentence. Your program should contain a function with the following header: int word_count(char str[]) or int word_count(char *str) This function takes in the sentence and counts the number of words in it. You may assume that there are at most 50 characters in the sentence At least one space is needed to separate words. For example, "J.K. Rowling" contains two words, but "J. K. Rowling" contains three. "A&W; fast-food" contains two words. A word must comprise at least one English letter. For example, "Jack & Jill potato chips" contains four words, not five, because "&" is not considered an English word. However, "Jack 'n Jill potato chips" contains five words, because "n" is considered a word as it contains the letter 'n'. Likewise, "3 + 5 is 8" contains only one word. You are to include in your program, but you are NOT allowed to use . This means that you are not allowed to use any string functions (yes, not even strlen()Explanation / Answer
#include <stdio.h>
#include <ctype.h>
#define LENGTH 50
int word_count(char[]);
int main(void) {
printf("Enter a sentence with at most %d characters: ", LENGTH);
char sentence[LENGTH] = "J. K. SRI";
printf("Sentence = %s ", sentence);
printf("Word count = %d ", word_count(sentence));
return 0;
}
// Count the number of words in str
int word_count(char str[]) {
int count = 0;
char temp[LENGTH] = { 0 };
int k = 0;
int alphaPresent = 0;
int i = 0;
for (i = 0; str[i] != ''; i++) {
temp[k] = str[i];
if (str[i] == ' ') {
temp[k] = '';
int j = 0;
while (1) {
if (temp[j] == '')
break;
else if ((isalpha(temp[j]) != 0)) {
alphaPresent = 1;
break;
}
j++;
}
if (alphaPresent == 1) {
++count;
}
k = -1;
temp[0] = '';
alphaPresent = 0;
}
k++;
}
alphaPresent = 0;
temp[k] = '';
int j = 0;
while (1) {
if (temp[j] == '')
break;
else if ((isalpha(temp[j]) != 0)) {
alphaPresent = 1;
break;
}
j++;
}
if (alphaPresent == 1) {
++count;
}
return count;
}
=============================
Enter a sentence with at most 50 characters:
Sentence = 3 + 5 is sri
Word count = 2
====
Enter a sentence with at most 50 characters:
Sentence = 3 + 5 is 8
Word count = 1
==========
Enter a sentence with at most 50 characters:
Sentence = J.K. SRI
Word count = 2
==
Enter a sentence with at most 50 characters:
Sentence = J. K. SRI
Word count = 3
====
Thanks
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.