Skip to content

Commit 37addb3

Browse files
authored
Merge pull request #112 from UG-SEP/UG
Added Count word.c Program
2 parents 14b848c + a0444ed commit 37addb3

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Strings/Count_word.c

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/* Program to find the total numbers of words in a sentence */
2+
#include<stdio.h>
3+
#include<string.h>
4+
#include<stdlib.h>
5+
6+
//Function which calculate and return total numbers of words
7+
int count_words(char *sen)
8+
{
9+
int i=0,check=1,word=0;
10+
//until i is less then length of sen variable the loop will run
11+
while(strlen(sen)>i)
12+
{
13+
/*if sen[i]th index value is not equal to space and i is not the last index number because
14+
the last index no. contain null and null is not alphabet so we not need to treat it as a alphabet*/
15+
if(sen[i]!=' '&&i!=strlen(sen)-1)
16+
{
17+
//if check is equal to 1(first time word occurrence after space)
18+
if(check==1)
19+
{
20+
//increment word and assign 0 to check
21+
word++;
22+
check=0;
23+
}
24+
}
25+
// if the sen[i]th index no. value is a space or null then run else
26+
else
27+
{
28+
//assign 1 to check
29+
check=1;
30+
}
31+
//increment i by 1
32+
i++;
33+
}
34+
return word;
35+
}
36+
//driver code
37+
int main()
38+
{
39+
//initialize required variables
40+
char *sen,res;
41+
// dynamically locating the address in sen variable
42+
sen=(char*)malloc(sizeof(char)*1000);
43+
printf("Enter a sentence: ");
44+
//taking input
45+
fgets(sen,1000,stdin);
46+
// resizing the sen variable length so memory wastage can be prevent
47+
sen=(char*)realloc(sen,strlen(sen)+1);
48+
// calling count_words function which will return total words in res variable
49+
res=count_words(sen);
50+
//printing the total words
51+
printf("Total number of words: %d",res);
52+
}
53+
/*
54+
Test case 1:
55+
Input: Enter a sentence: DSA is a Important Topic
56+
Output: Total number of words: 5
57+
58+
Test case 2:
59+
Input: Enter a sentence: Who are you?
60+
Output: Total number of words: 3
61+
62+
Time Complexity O(n) where n is the length of string
63+
64+
*/

0 commit comments

Comments
 (0)