Friday, July 31, 2009

C Programming Help? Word Count/Character Count Problem?

I need to write a program to perform word count/character count. I'm really stuck. Can anyone please help me out? Thanks





In this problem you are asked to analyze a string of characters and report the words contained within. The characters will be entered from the command line, and you may assume that no more than 512 characters will be entered. Your goal is to report the individual 'words' contained in the series of characters (a word is defined as any number of characters separated by spaces). You should also report the number of characters in each word, and the total number of words found. For this program you should not use %s to read the input. Instead you should use %c to read each character individually.





Sample Run:


Please enter some characters:


my name is


Word : Length


my : 2


name : 4


is : 2





Found 3 words

C Programming Help? Word Count/Character Count Problem?
This should work. You should familiarize yourself with the strtok function in C.





#include %26lt;stdio.h%26gt;


#include %26lt;string.h%26gt;





int main( int argc, char *argv[] ) {


int i = 0;


char *strPtr = NULL;


char str[512];





printf( "Please enter some characters:\n" );


do {


scanf( "%c", %26amp;str[i] );


i++;


} while( str[i - 1] != '\n' );





str[i - 1] = '\0';





i = 0;


printf( "Word:Length\n" );


strPtr = strtok( str, " " );


while( strPtr != NULL ) {


printf( "%s:%d\n", strPtr, strlen( strPtr ) );


i++;





strPtr = strtok( NULL, " " );


}





printf( "Found %d words.\n", i );





return( 0 );


}


No comments:

Post a Comment