Skip to content

Commit 9af68d5

Browse files
authored
added count word.c
1 parent 14b848c commit 9af68d5

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

Strings/Count_word.c

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

0 commit comments

Comments
 (0)