我写了一个应该从字符串中删除多余空格的程序。但它只显示空格前的字符。它找到一个空间并检查后面的字符是否是空格。根据多余的空间,它会将其他字符转移到多余的空间。但输出很混乱。一个从字符串中删除多余空格的程序
输入: “QWE(2位)RT(一个空格)y” 的
输出: “QWE(一个空格)RT(一个空格)y” 的
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int main(){
string a;
cin >> a;
int len = a.length();
int new_len=len;
int z,s=0;
for(int i=0; i<new_len; i++){
if(a[i]==' '){
z=i+1;
s=0;
//Assigning the number of excess spaces to s.
while(a[z]==' '){
s++;
z++;
}
//doing the shifting here.
if(s>0){
for(int l=i+1; l<new_len-s; l++){
a[l]=a[s+l];
}
}
new_len-=s;
}
}
cout << a << endl;
cout << a.length();
system("pause");
return 0;
}
你调试了你的代码吗? – Spook 2013-03-15 05:26:36
这是你想要做什么? http://stackoverflow.com/questions/8362094/replace-multiple-spaces-with-one-space-in-a-string – 2013-03-15 05:26:37
我会咨询[std :: string](http://en.cppreference.com/ w/cpp/string/basic_string),并考虑使用'find_first_of()'和'find_first_not_of()'及其模拟器来更有效地实现它。 – ChiefTwoPencils 2013-03-15 05:28:50