2014-02-19 145 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; 
}