分享两个函数
字符串函数经常用到,但是库函数的几个字符串函数总是喜欢不上来,每次都需要建立数组,太小了又不够,太大了又浪费空间,所以干脆自己写一个。我自己用着还挺好用。
这两个函数很大程度是一样的,但是我想了半天都没想到怎么精简。
getword()会跳过所有前导的非字母字符,但不会跳过字母中的非空白字符,同时会删除字符串最后的标点符号。
程序代码:测试:
#include <stdio.h>
#include <stdlib.h>
#include "getstring.h"
int
main( void )
{
FILE *fp;
char *str;
if( NULL == ( fp = fopen( "word.txt","r" ) ) )
{
fprintf( stderr, "Error: Failed to open file.\n" );
exit( EXIT_FAILURE );
}
while( NULL != ( str = getstring( fp ) ) )//从文件中读取
{
printf( "%s", str );
free( str );//需要手动释放内存,否则有可能造成内存泄漏。
}
printf( "\n" );
fseek( fp, 0, SEEK_SET );
while( NULL != ( str = getword( fp ) ) )//从文件中读取
{
printf( "%s ",str );
free( str );
}
str = getstring( stdin );//从标准输入读取
free( str );
fclose( fp );
return 0;
}
程序代码:#ifndef getstring_h #define getstring_h char * getstring( FILE *FP ); char * getword( FILE *FP ); #endif
程序代码:#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include "getstring.h"
#define INITSIZE 124
char *
getstring( FILE *FP )
{
char *Temp, *Str;
int CurrentSize, lx;
int ch;
CurrentSize = INITSIZE;
Temp = NULL;
Str = ( char * )malloc( INITSIZE * sizeof( char ) );
if( NULL != Str )
{
for( lx = 0; EOF != ( ch = getc(FP) ) && '\n' != ch; lx++ )
{
if( lx == CurrentSize - 1 )
{
CurrentSize += INITSIZE;
Temp = ( char * )realloc( Str, CurrentSize * sizeof( char ) );
if( NULL == Temp )
{
Str[ lx ] = '\0';
return Str;
}
Str = Temp;
}
Str[ lx ] = ch;
}
if( '\n' == ch )
Str[ lx++ ] = '\n';
Str[ lx ] = '\0';
if( 0 == lx )
{
free( Str );
Str = NULL;
return Str;
}
if( lx < CurrentSize )
{
Temp = ( char * )realloc( Str, ( lx + 1 ) * sizeof( char ) );
if( NULL == Temp )
return Str;
Str = Temp;
}
return Str;
}
else
return NULL;
}
char *
getword( FILE *FP )
{
char *Word, *Temp;
int ch;
int lx, CurrentSize;
CurrentSize = INITSIZE;
Temp = NULL;
Word = ( char * )malloc( CurrentSize * sizeof( char ) );
while( !isalpha( ch = getc( FP ) ) && EOF != ch )
;
if( NULL != Word )
{
for( lx = 0; EOF != ch && !isspace( ch ); lx++, ch = getc( FP ) )
{
if( lx == CurrentSize - 1 )
{
CurrentSize += INITSIZE;
Temp = ( char * )realloc( Word, CurrentSize * sizeof( char ) );
if( NULL == Temp )
{
Word[ lx ] = '\0';
return Word;
}
Word = Temp;
}
Word[ lx ] = ch;
}
if( 0 == lx )
{
free( Word );
Word = NULL;
return Word;
}
if( lx < CurrentSize )
{
Temp = ( char * )realloc( Word, ( lx + 1 ) * sizeof( char ) );
if( NULL == Temp )
{
Word[ lx ] = '\0';
return Word;
}
Word = Temp;
}
if( ispunct( Word[ lx - 1 ] ) )
{
Word[ --lx ] = '\0';
return Word;
}
Word[ lx ] = '\0';
return Word;
}
else
return NULL;
}
[此贴子已经被作者于2017-3-20 08:40编辑过]



