Here we will count the number of times a word is found in a user input. We will be first counting the number of words and then adding a count bit at the end of each word and then count the occurrences of each word and display.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
#include <iostream.h> #include <conio.h> #include <string.h> void main(){ int i,j,wordi,wordc=0,word_array=0,count; char string[1000],words[100][30]; clrscr(); cout << "Enter the paragraph"<<endl; cin.getline(string,1000); cout <<endl; for(i=0;i<strlen(string);){ //strip any spaces at the start (not actually but logically) if(i==0){ if((int)string[0]==32){ while((int)string[i]==32) { i++; } } } //now start counting words if((int)string[i]==32){ wordc++; while((int)string[i]==32){ i++; } } else { i++; } } // add an extra count due to space //between words being less than no of words if((int)string[strlen(string)-1]==32) { } else { wordc++; } // save words to array for(i=0;i<strlen(string);i++){ // move i to the character other then space if((int)string[0]!=32){ while((int)string[i]==32){ i++; } } wordi=0; //save words while((int)string[i]!=32){ words[word_array][wordi]=string[i]; wordi++; i++; if((int)string[i]=='\0') string[i]=(char)32; } words[word_array][wordi]='0'; //Add counter bit words[word_array][wordi+1]='\0'; word_array++; } // for ends // count the occurences of each word for(i=0;i<wordc;i++){ count=1; for(j=i+1;j<=wordc;j++){ if(strcmp(words[i],words[j])==0 && words[j][strlen(words[j])-1]=='0'){ words[j][strlen(words[j])-1]='1'; count++; } } // display the count of each word if(words[i][strlen(words[i])-1]=='0'){ words[i][strlen(words[i])-1]='\0'; cout <<words[i] << " : " ; cout << count <<endl; } } getch(); } |
Compiled with TurboC3
Alternative Solution : By Karan (YMCA University)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
#include<stdio.h> #include<string.h> #include<conio.h> struct word { char name[50]; int count; }; void main() { struct word arr[100]; char str[200],buffer[50]; int i=0,j=0,k=0,l; clrscr(); printf("enter the string:"); gets(str); for(i=0; str[i]!='\0'; i++) { if(str[i+1]!=' '&& str[i+1]!='\0')buffer[j++]=str[i]; else if(str[i+1]==' '|| str[i+1]=='\0') { buffer[j++]=str[i]; buffer[j]='\0'; j=0; if(str[i+1]==' ') { i++; } for(l=0;l<k;l++) { if(strcmp(arr[l].name,buffer)==0) { arr[l].count++; break; } } if(l>=k) { strcpy(arr[k].name,buffer); arr[k++].count=1; } } } printf(" word :: count \n"); for(i=0; i<k; i++) { printf(" %s \t %d \n",arr[i].name,arr[i].count); } getch(); } |
Compiled With TurboC3