【问题标题】:Can I use str.append to create a new string with no vowels?我可以使用 str.append 创建一个没有元音的新字符串吗?
【发布时间】:2021-12-24 12:38:28
【问题描述】:

我正在从 codewars.com 做一个练习作业,以创建一个程序,该程序将采用巨魔的 cmets 并将其转换为没有元音的语句。

我的想法是获取注释,返回所有不是元音的字符,然后使用迭代器将其放入一个新的字符串数组中。

int main()
{
    string troll;
    string disemvoweled;
    
    getline(cin,troll);
    int length= (int) troll.length();
    
    string::iterator it;
    
    for (it = troll.begin();it!=troll.end();it++) {
        if (*it!='a' || *it!='e' || *it!='i' || *it!='o' || *it!='u' || *it!='A' || *it!='E' ||*it!='I' || *it!='O' || *it!='U'){
            disemvoweled.append(*it);
        }
    }
    cout << disemvoweled;

    return 0;
}

我收到一个错误:

no matching function for call to std::__cxx11::basic_string<char>::append(char&)'

我的第一个问题是为什么 append() 不起作用?

我的第二个问题是,在没有提供任何解决方案的情况下,C++ 的哪个概念可以帮助我改进这段代码?我在想也许使用某种容器并弹出一个元音?

【问题讨论】:

  • 您不能直接将字符附加到字符串。对于您的最终解决方案,请查看以下构建块:std::set(元音)、std::ostringstream(字符串构建)和基于范围的 for 循环(比迭代器循环更具可读性)。
  • 还有一个逻辑错误 - 如果所有 != eval 都为 true,您只想追加,所以所有 ors (||) 都应该是 ands (&&)

标签: c++ string iterator append


【解决方案1】:

为什么 append() 不起作用?

append 的重载可以在 here 中找到,正如您所见,它们期望不同类型的参数(如 const std::string&amp;const char*),而您提供 char 类型参数。

您可以使用+= 解决此问题,如下所示:

disemvoweled+= (*it);

C++ 的哪个概念可以帮助我改进这段代码?

您可以使用std::set 改进代码,如下所示:

getline(cin,troll);
std::set<char> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E','I','O','U'};

for (auto it = troll.begin();it!=troll.end();it++) {
    if (vowels.find(*it) == vowels.end())
    {
        disemvoweled+= (*it); //can also use disemvoweled.append(1, *it);
    }
}
cout << disemvoweled;

【讨论】:

  • 也可以使用push_back
  • @Yes 但 IMO += 是最简单的。
【解决方案2】:

你可以使用range-v3:

#include <string>
#include <iostream>

#include <range/v3/all.hpp>

constexpr bool is_not_vowel(char const ch) noexcept {
    switch (ch) {
        case 'a': case 'e': case 'i': case 'o': case 'u': 
        case 'A': case 'E': case 'I': case 'O': case 'U':
            return false;
        default:
            return true;
    }
}

int main() {
    std::string str = "hello world";
    std::string no_vowels;
    ranges::copy(
        str | ranges::views::filter(is_not_vowel),
        std::back_inserter(no_vowels)
    );

    std::cout << no_vowels << '\n';
}

See online

【讨论】:

    猜你喜欢
    • 2020-11-28
    • 2019-07-24
    • 2021-04-22
    • 2019-08-11
    • 2019-05-18
    • 2016-05-12
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多