标签:
/**
* 功能:
* 1、去除字符串两边的空白字符
* 2、将字符串中间的连续空白字符压缩为一个空格
*
* 时间:2015/10/17 15:10:49
* 作者:小代码
*
*/
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
/**
* @brief 将字符串两人边的空白字符删除,并返回一个新的字符串
*
* @param str 要处理的字符串
*
* @return 返回删除两边空白字符的新字符串
*/
char * str_trim( char * str ){
int str_len = strlen( str );
int begin = 0;
int end = str_len - 1;
int i = 0;
while( isspace( str[ begin++ ] ) ) ;
begin--;
while( isspace( str[ end-- ] ) ) ;
end++;
char *t = ( char* )malloc( sizeof( char )*( end - begin + 2 ) );
i = 0;
while( begin <= end && ( t[ i++ ] = str[ begin++ ] )) ;
t[ i ] = ‘\0‘;
return t;
}
/**
* @brief 将字符串中间的空白字符压缩为一个空格,并返回新的字符串
*
* @pre 字符串两人边不能有空白字符
* @param 要处理的字符串
*
* @return 返回连续空白转换为一个空格的字符串
*
*/
char * str_constrict_space( char * str ){
int str_len = strlen( str );
char * t = ( char* )malloc( sizeof( str_len ) * str_len );
int i = -1;
int j = 0;
while( i++ < str_len ){
if( !isspace( str[ i ] ) ){
t[ j++ ] = str[ i ];
}else{
if( !isspace( str[ i+1 ] ) ){
t[ j++ ] = ‘ ‘;
}
}
}
t[ j ] = ‘\0‘;
return t;
}
int main( void ){
char str[ 30 ];
fgets( str,30,stdin );
char * t = str_trim( str );
printf( "**%s**\n",t );
t = str_constrict_space( t );
printf( "%s\n", t);
}
运行效果:
[laolang@laolang string]$ make exec ./hello 123 456 **123 456** 123 456 [laolang@laolang string]$
标签:
原文地址:http://my.oschina.net/iamhere/blog/518280