c program

2007-08-23 6:57 am
點樣先可以用c program數一段文中出現某字詞的次數
例如:
i am a good boy.
i am a student.
i am a child.
先後就數....;
i出現了3次~
am出現了3次
a出現了3次
good boy1次
child1次
student1次
我想做到每次用唔同txt file都做到~
請幫忙~
更新1:

not work...~

回答 (1)

2007-08-23 11:34 pm
✔ 最佳答案
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?


收錄日期: 2021-04-21 13:16:29
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20070822000051KK06172

檢視 Wayback Machine 備份