给定字符串,删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个。
比如 “ I like http://blog.youkuaiyun.com/yake25 ” 会变成 "I like http://blog.youkuaiyun.com/yake25"。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int SIZE = 1024;
char str[SIZE];
char newstr[SIZE];
void delStr(char *str)
{
memset(newstr, 0, SIZE);
bool flag = false;
int j = 0;
for(int i = 0; str[i]; i++)
{
if(str[i] != ' ')
{
str[j++] = str[i];
flag = true;
}
else
{
if(flag)
{
str[j++] = ' ';
flag = false;
}
}
}
if(j > 0 && str[j-1] == ' ')
str[j-1] = '\0';
else
str[j] = '\0';
}
int main()
{
while(gets(str))
{
FILE *fp;
fp = fopen("result.txt", "w+");
cout << "Input string: " << str << endl;
delStr(str);
//cout << "DeleteSpace string: " << str << endl;
fputs(str, fp);
}
}
本文介绍了一种用于处理字符串中多余空格的算法实现。该算法可以移除字符串首尾的空白字符,并将字符串中间多余的连续空白字符压缩为单个空格。文中提供了一个具体的C++实现示例。
2797

被折叠的 条评论
为什么被折叠?



