Friday, July 31, 2009

C++ Counting the number of words in a string?

How would you go about counting the number of words in a string and the number of occurences of each individual letter? Is there an easy way to do the counting or will I need to create like 26 different loops to do the counting?

C++ Counting the number of words in a string?
***note: the following code may not be completely accurate. it is meant to show a way to get the solution, but there may be bugs.





basically:





1) keep track of a word count using the # of spaces there are, not counting the 1st or last position.





2) keep track of a letter count, with the index of the array being the letter, and the contents being the # of occurances of that letter.





---





#include %26lt;stdio.h%26gt; /* standard in/output include file */


#include %26lt;string.h%26gt; /* include file for string functions */








#define MAXlength 50 /* max. length of test_string */








main()


{


char i, /* used as a counter */


ch, /* a temporary character */


strsz; /* the length of the string */





char test_string[MAXlength]; /* the string being dealt with */


char alpha_count[26]; /* the letter count (of 'aA'-'zZ') */


char word_count=0; /* the word count */





for(i=0;i%26lt;26;i++)


alpha_count[i]=0; /* set counts of letters to 0 */





/* --- insert code here for inputting the string from the user */





strsz=strlen(test_string); /*sets strsz to the lngth of the string */





for(i=0;i%26lt;strsz;i++) /* go through each character of the string */


{


if(test_string[i]==' ') /*if it's a space, and the space */


if((i%26gt;0)%26amp;%26amp;(i%26lt;(strsz-1)) /* is not at the beginning or end of */


word_count++; /* the string, increase the wordct. */





ch=toupper(test_string[i]); /* ch = uppercase of the letter */





if((ch%26gt;='A')%26amp;%26amp;(ch%26lt;='Z')) /* if it's a letter between 'A'-'Z' */


alpha_count[ch-'A']++; /* keep track of that letter */


}





printf("In '%s':\n,test_string);


printf("There are %d words.\n",word_count);


for(i=0;i%26lt;26;i++)


if(alpha_count[i]%26gt;0) /* don't show counts for letters that */


/* aren't there */


printf("There are %d '%c's\n",alpha_count[i],'a'+i);


}

wedding reception flowers

No comments:

Post a Comment