2016-05-10 65 views
0

以下是用'%20'替換字符串中的所有空格的方法。它通常工作正常,但在執行完成'運行時檢查失敗#2 - S'時抱怨。我的for循環有問題嗎?運行時檢查失敗#2 - S,Visual Studio C++

void replaceSpace(char *s) { 
    int spaces = 0; 
    for (int i = 0; i < strlen(s); i++) { 
     if (s[i] == ' ') { 
      spaces++; 
     } 
    } 

    // new string that includes overwriting space, and two additional chars 
    int newLen = strlen(s) + spaces * 2; 

    s[newLen] = '\0'; 
    for (int i = strlen(s) - 1; i >= 0; i--) { 
     if (s[i] == ' ') { 
      s[newLen - 1] = '0'; 
      s[newLen - 2] = '2'; 
      s[newLen - 3] = '%'; 
      newLen -= 3; 
     } 
     else { 
      s[newLen - 1] = s[i]; 
      --newLen; 
     } 
    } 
} 




char test[] = "rep lace Spac e"; 
replaceSpace(test); 
cout << test << endl; //rep%20lace%20Spac%20e 

編輯:我跑了這cpp shell,並沒有任何問題奇怪。我試着更新visual studio 2015,然後回報。

edit2:不,同樣的錯誤。

+0

*貌似*工作是未定義行爲的可能性之一。 –

回答

1

當你定義test

char test[] = "rep lace Spac e"; 

你定義的正是 16個字符(不要忘記字符串結束)的陣列。沒有辦法擴展數組,這意味着你會寫出數組的邊界,導致未定義的行爲

解決方案當然是用std::string代替,而加上就可以了。

+0

真的沒有其他辦法嗎?在java中的實現似乎沒有問題。我當然可以簡單地使用std :: replace,但我正在練習實現。 – blueman

+1

@mannerofallthings數組的大小是固定的,就是這樣。如果你想擴展字符串(就像用三個字符替換一個字符),那麼你需要一些動態數據結構,比如標準的'std :: string'類。 –

0

真的,這段代碼沒有必要。檢查它:

#include <iostream> 
#include <string> 
#include <algorithm> 
#include <cctype> 

int main() 
{ 
    std::string s("rep lace Spac e"); 
    s.erase(std::remove_if(s.begin(), s.end(), static_cast<int(*)(int)>(std::isspace)), s.end()); 
    std::cout << s; 
} 
+0

需要解釋如何以及爲什麼這個工程,否則你只是促進[貨物崇拜編程](https://en.wikipedia.org/wiki/Cargo_cult_programming) – user4581301

+0

OP希望所有空間替換爲「%20」,而不是簡單地刪除。 –

相關問題