字符串错误输出

String error output

本文关键字:输出 错误 字符串      更新时间:2023-10-16

我得到了一个代码。它应该给我一个输出,可以擦除"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;
}

当我替换 a[i+1] = ''; 它给了我一个错误。

您不是删除字符,而是用 ' ' 替换它们。

有很多方法可以做到这一点。一种简单的方法是构建一个新字符串,仅在满足适当条件时才添加字符:

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;
}

使用 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;
}

您完全正确,不能将字符串的元素替换为"。字符串是字符数组,而 '' 根本不是字符。这不算什么。如果我们查看 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;

希望有帮助

如果#include <regex>,则可以执行正则表达式替换。

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