去除字符串中多于的空格

zhouhong0801 2007-10-27 09:13:14
实现对字符串的处理:首先将该字符串首尾的空格去掉,如果字符串中间还有连续空格,仅保留一个空格,即允许字符串中间有多个空格,但连续的空格数不可超过一个。
...全文
222 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
mLee79 2007-10-29
  • 打赏
  • 举报
回复

#include <stdio.h>
#include <string.h>

char* slove( char* s )
{
char *p1 = s , *p2 = s;
while( *p2 == ' ' ) ++p2;
if( !*p2 ) return *s = 0 , s;
*p1++ = *p2++;
for( ; *p2 ; ++p2 )
if( *p2 != ' ' || p1[-1] != ' ' )
*p1++ = *p2;
p1[ p1[-1]==' '?-1:0 ] = 0;
return s;
}

int main()
{
char line [ 1024 + 1 ] = "";
while( gets( line ) )
{
int len = strlen( line );
printf( "result : [[[%s]]]\n" , slove(line) );
}
return 0;
}

daidodo 2007-10-29
  • 打赏
  • 举报
回复
遍历一次:
#include <iostream>
#include <string>
#include <cctype>

using namespace std;

string RemoveSpace(string input)
{
string result;
int lastch = 0;
for(size_t i = 0;i < input.length();++i){
if(isspace(input[i])){
if(lastch == ' ')
continue;
lastch = ' ';
}else{
if(lastch == ' ' && !result.empty())
result.push_back(' ');
result.push_back(input[i]);
lastch = input[i];
}
}
return result;
}

int main()
{
char buf[1024];
cout<<"input a string:";
cin.getline(buf,1024);
cout<<"output: <"<<RemoveSpace(string(buf))<<">"<<endl;
}
zhouhong0801 2007-10-28
  • 打赏
  • 举报
回复
能不能有O(n)的方法呀?

最好要高效一点
william484 2007-10-28
  • 打赏
  • 举报
回复
有o(n^2)的方法;
O(n)的没想出来
一定要扫描一次字符串,如果发现空格的话还要继续扫描一共有几个空格再做相应的处理
看来要想想数学方法了
飞哥 2007-10-27
  • 打赏
  • 举报
回复
最笨的办法就可以了


while(...)
{

switch(ch)
{
case 0x20:
//,.,,,,
break;
}
}

70,020

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧