我寫了一個應該從字符串中刪除多餘空格的程序。但它只顯示空格前的字符。它找到一個空間並檢查後面的字符是否是空格。根據多餘的空間,它會將其他字符轉移到多餘的空間。但輸出很混亂。一個從字符串中刪除多餘空格的程序
輸入: 「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