Write a C program to calculate the number of words in a string.
#include <stdio.h>
#include <string.h>
int main() {
char str[512];
int i = 0, words = 0, n;
/* get the input string from the user */
printf("Enter your input string:");
fgets(str, 512, stdin);
str[strlen(str) - 1] = '\0';
/*
* if the 1st character in input string is
* null, then number of words is zero
*/
if (str[0] == '\0') {
printf("No of words in the given string is 0\n");
return 0;
}
/* calculate the number of words */
while (str[i] != '\0') {
if (str[i] == ' ')
words++;
i++;
}
/* print the number of words */
printf("Number of words in the given string is %d\n", words + 1);
return 0;
}
#include <string.h>
int main() {
char str[512];
int i = 0, words = 0, n;
/* get the input string from the user */
printf("Enter your input string:");
fgets(str, 512, stdin);
str[strlen(str) - 1] = '\0';
/*
* if the 1st character in input string is
* null, then number of words is zero
*/
if (str[0] == '\0') {
printf("No of words in the given string is 0\n");
return 0;
}
/* calculate the number of words */
while (str[i] != '\0') {
if (str[i] == ' ')
words++;
i++;
}
/* print the number of words */
printf("Number of words in the given string is %d\n", words + 1);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your input string:Hello Friend!! How Are You?
Number of words in the given string is 5
Enter your input string:Hello Friend!! How Are You?
Number of words in the given string is 5
No comments:
Post a Comment