给定字符串,删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个。
比如 “ I like http://blog.csdn.net/yake25 ” 会变成 "I like http://blog.csdn.net/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);
}
}