gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:07:15 26 4
gpt4 key购买 nike

尝试做一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com