✔ 最佳答案
try following code:
#include <stdio.h>;
#include <string.h>;
/* Global Variables setup */
char cChk[ 256 ][ 256 ];
int nCnt[ 256 ];
/* Function Prototype */
void DelimStr( char * );
void CntStr( char * );
void ShowCnt( );
int main(int argc, char *argv[ ])
{
FILE *FPtr;
char *cptr;
char buffer[256];
printf( "%s\n", argv[1] );
/* File I/O */
if ( ( FPtr = fopen( argv[1], "r" ) ) == NULL )
{ printf( "FILE CANNOT OPEN!!!\n" );
return -1;
}
/* Get file string line by line */
while( !feof( FPtr ) )
{ cptr = fgets( buffer, 256, FPtr );
if ( cptr == NULL )
break;
/* Reset new line ('\n' ) */
cptr[ strlen( cptr ) - 2 ] = '\0';
DelimStr( strncpy( cptr, cptr, strlen( cptr ) - 1 ) );
}
ShowCnt( );
return 0;
}
/* Get string token */
void DelimStr( char *str )
{ char *result = NULL;
result = strtok( str, " " );
while( result != NULL )
{ CntStr( result );
result = strtok( NULL, " " );
}
}
/* Count string */
void CntStr( char *str )
{ int i = 0;
for ( i = 0; i < 256; i++ )
{ /* New string */
if ( strcmp( cChk[ i ], "" ) == 0 )
{ strcpy( cChk[ i ], str );
nCnt[ i ] = 1;
break;
}
/* Increment count for existing string */
if ( strcmp( cChk[ i ], str ) == 0 )
{ nCnt[ i ]++;
break;
}
}
}
/* Show count result */
void ShowCnt( )
{ int i = 0;
for ( i = 0; i < 256; i++ )
{ if ( strcmp( cChk[ i ], "" ) == 0 )
return;
printf( "%s -- %d\n", cChk[ i ], nCnt[ i ] );
}
}
Execution:
let the executable file is named CntStr.exe. It can be run with:
CntStr c:\abc.txt if u want to count the text file is c:\abc.txt
Assumption:
- less than 256 characters per a line in the text file.
- less than 256 team of string need to count.
OK?