统计文本中最长单词的长度
如何统计文本中最长单词的长度,我想把一系列单词存在二维数组中,然后调用strlen函数计算每个单词长度把这些数据存在另一个数组中,再比较。求解如何将几个单词存入二维数组
程序代码:char *
max_len ( FILE * stream )
{
char * max_str = NULL, * temp_str ;
unsigned max_len = 0, temp_len ;
int i = 0 ;
if ( stream == NULL ) {
return NULL ;
}
while ( fscanf ( stream, "%s", temp_str ) == 1 ) {
temp_len = strlen ( temp_str ) ;
/*
**判断字符串是否为英文单词
*/
while ( isalpha ( *(temp_str + i++) ) ) {
//nothing
}
if ( i < temp_len ){
continue ;
}
/*
**判断单词长度
*/
if ( max_len < temp_len ){
max_len = temp_len ;
max_str = temp_str ;
}
}
return max_str ;
}
程序代码:#include<stdio.h>
#include<string.h>
#define N 30 //假设单词的最大长度为30 ,这里为了方便没有利用动态内存分配
char *max_len ( FILE * stream )
{
static char max_str[N];//静态变量,全局有效 (防止函数返回后释放掉该内存区域)
char temp_str[N];//局部变量,局部有效
unsigned max_len = 0, temp_len ;
int i = 0 ;
if ( stream == NULL ) {
return NULL ;
}
while ( fscanf ( stream, "%s", temp_str ) == 1 ) {
temp_len = strlen ( temp_str ) ;
/*
**判断字符串是否为英文单词
*/
while ( isalpha ( *(temp_str + i++) ) ) {
//nothing
}
if ( i < temp_len ){
continue ;
}
/*
**判断单词长度
*/
if ( max_len < temp_len ){
max_len = temp_len ;
strcpy(max_str,temp_str) ;
}
}
return max_str ;//返回指向max_str数组的指针值
}
int main (void)
{
FILE *fp=NULL;
if((fp=fopen("d:\\test.txt","r"))==NULL)//注意,测试时改变你的测试文件的地址
{
printf("open the file is error!\n");
exit(0);
}
printf("最长字符为:%s",max_len(fp));
close(fp);
getchar();
return 0;
}
