2014-02-19 149 views
-2

我得到了一個代碼。它應該給我一個輸出,可以擦除'z'和'p'之間的中間字符。例如:zipZap( 「zipXzap」):預期[zpXzp]但發現[Z PXZ P]字符串錯誤輸出

std::string zipZap(const std::string& str){ 
    string a = str; 
    string b = ""; 
    size_t len = str.length(); 
    for (size_t i = 0; i < len; i++){ 
     if (str[i] == 'z') 
      if (str[i+2] == 'p') 
       a[i+1] = ' '; 
    } 
    return a; 
} 

在i取代了第[i + 1] = '';它給了我一個錯誤。

+0

它做了你想做的事情。刪除z和p之間的字符。 –

+1

好吧,它不會刪除任何字符。它用空格替換它們。 –

+3

你的代碼有'a [i + 1] =''',它將*空格*放在那裏,而不是刪除現有的字符。 – crashmstr

回答

0

您不會刪除字符,而是用' '替換它們。

有很多方法可以做到這一點。一個簡單的方法是建立一個新的字符串,只增加字符時,適當的條件得到滿足:

std::string zipZap(const std::string& str) 
{ 
    string a; 
    size_t len = str.length(); 
    for (size_t i = 0; i < len; i++) { 
     // Always add first and last chars. As well as ones not between 'z' and 'p' 
     if (i == 0 || i == len-1 || (str[i-1] != 'z' && str[i+1] != 'p')) { 
      a += str[i]; 
     } 
    } 
    return a; 
} 
0

使用string.erase():

std::string zipZap(const std::string& str){ 
    std::string a = str; 
    std::string b = ""; 
    size_t len = str.length(); 
    for (size_t i = 0; i < len; i++){ 
     if (a[i] == 'z') 
      if (a[i+2] == 'p') 
       a.erase(i+1,1); 
    } 
    return a; 
} 
0

你,你不能完全替代權帶''的字符串的一個元素。 一個字符串是一個字符數組,而''根本不是字符。沒什麼。 如果我們看一下CPLUSPLUS頁字符串

http://www.cplusplus.com/reference/string/string/

我們看到,我們可以使用erase(iterator p)「從字符串刪除字符(公共成員函數)」

因此,如果我們改變:

for (size_t i = 0; i < len; i++){ 
    if (str[i] == 'z') 
     if (str[i+2] == 'p') 
      a.erase(a.begin() + i + 1); 

我們現在更近了,但我們可以看到len不再與str.length()相同。 a的長度現在實際上比len短1個字符。爲了解決這個問題但是我們可以簡單地添加:

for (size_t i = 0; i < len; i++){ 
    if (str[i] == 'z') 
     if (str[i+2] == 'p') 
      a.erase(a.begin() + i + 1); 
      len -= 1; 

希望幫助

0

如果#include <regex>,你可以做一個正則表達式替換。

std::string zipZap(const std::string& str){ 
    regex exp("z.p"); 
    string a = str; 
    a = regex_replace(a, exp "zp"); 
    return a; 
}