【发布时间】:2013-03-15 15:12:12
【问题描述】:
我写了一个程序,它应该从字符串中删除多余的空格。但它只在空格前显示字符。它找到一个空格并检查之后的字符是否是空格。根据多余的空格,它将其他字符移动到多余的空格上。但是输出很混乱。
输入:“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;
}
【问题讨论】:
-
你调试过你的代码吗?
-
这是你想要做的吗? stackoverflow.com/questions/8362094/…
-
我会咨询 std::string 并考虑使用
find_first_of()和find_first_not_of()及其类似物来提高效率。 -
std::string a; cin >> a;跳过前导空格,仅将数据读入a,直到遇到更多空格(不会读入a)或文件结尾,所以你不能可能有任何空白要删除的输入。如果您将cout << "a '" << a << "'\n";放入您的程序中,您会注意到:这样的“跟踪”输出对于编程来说是必不可少的诊断,并且可以让您观察您的程序工作......