2013-03-15 103 views
0

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

輸入: 「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; 
} 
+0

你調試了你的代碼嗎? – Spook 2013-03-15 05:26:36

+2

這是你想要做什麼? http://stackoverflow.com/questions/8362094/replace-multiple-spaces-with-one-space-in-a-string – 2013-03-15 05:26:37

+0

我會諮詢[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

回答

1

大部分代碼是半無意義的 - 當您使用普通字符串提取器(stream >> string)時,它會自動跳過所有連續的前導空格,並停止讀取第一個空格字符。因此,它已經在完成其他代碼的所有工作。這使得一個更簡單的方法來完成相同的任務:

std::copy(std::istream_iterator<std::string>(std::cin), 
      std::istream_iterator<std::string>(), 
      std::ostream_iterator<std::string>(std::cout, " ")); 

這確實有一個問題:它會在輸出的年底留下一個額外的空間。如果你不想這樣做,你可以使用我之前發佈的infix_ostream_iterator。就這樣,你上面的改變是這樣的:

std::copy(std::istream_iterator<std::string>(std::cin), 
      std::istream_iterator<std::string>(), 
      infix_ostream_iterator<std::string>(std::cout, " ")); 
+0

我不明白這段代碼。但它可能是解決方案。 – bbilegt 2013-03-15 07:32:21

1

你的代碼是高度無效的。想象一下,下面的字符串包含1,000,000個字符:

a a a a a a a... 

每次你的算法遇到的第二空間,它通過整個字符串來接班一個字符左邊。我會嘗試另一種方法:

  • 創建兩個迭代器,如realPos和charPos。在開始時將它們設置爲0。
  • 創建一個變量,該變量存儲目前爲止遇到的大量空間,如spacesSeen。將它設置爲0。
  • 現在,雖然realPos比整個字符串的長度降低:
    • 如果string[realPos] != ' 'charPos != realPos,進行分配:string[charPos] = string[realPos]。然後將realPoscharPos都加1。將空格設置爲0.
    • 如果string[realPos] == ' 'spacesSeen == 0,則將spacesSeen增加1,複製字符並同時推進兩個迭代器。
    • 如果string[realPos] == ' 'spacesSeen > 0,則增加spacesSeen,然後僅增加realPos
  • 現在charPos標誌着最後一個字符串結束的位置,調整字符串的大小,使它在那裏結束。

簡單的說法是:逐個複製字符,並在路上跳過多個空格。

+0

它是有幫助的。 – bbilegt 2013-03-15 07:08:36

1

如果您使用C++ 11這樣你的方式是矯枉過正 - 你可以使用正則表達式。類似下面的內容應該這樣做(未經測試):

#include <regex> 
#include <iostream> 
#include <string> 
using namespace::std; 

int main(){ 
    string a; 
    cin >> a; 
    regex r(" +"); 
    a = regex_replace(a,r," "); 
    cout << a << endl; 
    cout << a.length(); 
    system("pause"); 
    return 0; 
} 
相關問題