c++ - 如何忽略字符数组中的某些字母和空格

标签 c++ arrays

尝试做一个 else 声明,去掉所有其他字母和空格,然后是我想要的。这个函数是将用户输入的字母变成其他字母

using namespace std;
    void dna_to_rna(char rna[]) 
    {
        for (int i = 0; i < 100; i++)
        {
            if (rna[i] == 'a' || rna[i] == 'A')
                rna[i] = 'U';
            else if (rna[i] == 'c' || rna[i] == 'C')
                rna[i] = 'G';
            else if (rna[i] == 'g' || rna[i] == 'G')
                rna[i] = 'C';
            else if (rna[i] == 't' || rna[i] == 'T')
                rna[i] = 'A';
}

为了删除所有其他字符,else 语句应该是什么样子?

最佳答案

如果输入参数可以更改为std::string,那么您可以使用以下实现之一:

void dna_to_rna(std::string& rna)
{
    auto it = rna.begin();
    while (it != rna.end())
    {
        if      (*it == 'a' || *it == 'A') *it = 'U';
        else if (*it == 'c' || *it == 'C') *it = 'G';
        else if (*it == 'g' || *it == 'G') *it = 'C';
        else if (*it == 't' || *it == 'T') *it = 'A';
        else
        {
            it = rna.erase(it);
            continue;   // it already "points" to the next element
        }

        ++it;
    }
}

std::string dna_to_rna(const std::string& dna)
{
    std::string rna;
    for (auto c : dna)
    {
        if      (c == 'a' || c == 'A') rna += 'U';
        else if (c == 'c' || c == 'C') rna += 'G';
        else if (c == 'g' || c == 'G') rna += 'C';
        else if (c == 't' || c == 'T') rna += 'A';
    }

    return rna;
}

关于c++ - 如何忽略字符数组中的某些字母和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37021428/

相关文章:

javascript - 如何过滤掉数组中的 NaN, null, 0, false (JS)

c - 在c中将值写入二维数组

c++ - 用于运算符重载的 Lambda 表达式

c++ - double 到 time 的转换

c++ - 在 Windows 屏幕上渲染缓冲区

c - 我正在尝试在 C 中实现二进制搜索,但它显示运行时错误。我从互联网上获取了代码

c - 在 C 中包含数组索引是一种好习惯吗?

c++ - VC++ 函数 string::c_str(): 第一个字节的地址被设置为 0(与 g++ 比较)

c# - C++ 中的变量变量名

c++ - 如何创建模板化类对象数组?