一道笔试题,去除首尾空白符,中间若有连续空格则保留一个,若出现换行则保留一个换行

来源:互联网 发布:预算通软件 编辑:程序博客网 时间:2024/06/10 22:27

比如:

"  \n  \n  a b  \nc \n  \n\nc\nde f    g\n\nhi\n\n\n  \n  "

处理后变为:

“a b\nc\nc\nde f g\nhi”

这里,空白符只考虑空格和换行,若连续的空格超过两个,则留一个;若连续空白符中出续换行,则留一个换行而不留空格。

实现过程比较绕,写下面备忘。

1. 先分别去除首尾空白符。这比较简单,只不过要注意字符的长度也跟着变化。

2。处理中间部分:则4个变量:

int i; 将被替换的位置。

int j;每次循环都自增,用于判断字符的状况。

int cnt;记录连续空白符的个数。

bool b; 记录连续空白符中是否出现换行。

代码如下(还可优化):

int trim( char* str, int len ){if( str == NULL || *str == 0 )return 0;//去头while( *str == ' ' ||  *str == '\n' ){++str;--len;}//去尾while( *(str+len-1) == ' ' ||  *(str+len-1) == '\n' )--len;*(str+len) = 0;printf("去首尾空白符后\n%s\n",str);int i=0,j=0,cnt=0;bool b = false;for (;j<len;++j){if( str[j] == ' ' || str[j] == '\n' )++cnt;elsecnt = 0;if( str[j] == '\n' && cnt >= 2 )b = true;else if( cnt == 0 )b = false;if(  i != j  ){if(b)str[i-1] = '\n';str[i] = str[j];}if(cnt < 2) ++i;}str[i] = 0;printf("最后字串:\n%s\n",str);return i;}int _tmain(int argc,char* argv[]){const int N = 100;char a[N] = "  \n  \n  a b  \nc \n  \n\nc\nde f    g\n\nhi\n\n\n  \n  ";trim(a,strlen(a));return 0;}
输出:

去首尾空白符后a bccde f    ghi最后字串:a bccde f ghi请按任意键继续. . .
上述时间复杂度为O(n),辅助空间为O(1)。代码还可优化,比如当 i != j时,若j处在连续空白状态,可以不用换,不过这样写起来太绕,就不这么做了。

原创粉丝点击