gpt4 book ai didi

c++ - 如何检查字符是否包含特定字母

转载 作者:行者123 更新时间:2023-11-30 05:19:48 26 4
gpt4 key购买 nike

我正在尝试编写代码来检查一个字符包含多少个“A”、“C”、“G”和“T”字符。但我有点不确定如何去做这件事……因为据我所知,没有像 .contains() 这样的运算符可供检查。

所需的输出类似于:

"The char contains (variable amount) of letter A's"

在我的代码中,我现在有这个:

DNAnt countDNAnt(char strand)
{
DNAnt DNA;

if (isupper(strand) == "A")
{
DNA.adenine++;
}
else if (isupper(strand) == "C")
{
DNA.cytosine++;
}
else if (isupper(strand) == "G")
{
DNA.guanine++;
}
else if (isupper(strand) == "T")
{
DNA.thymine++;
}
}

DNAnt 是一种结构,它具有我正在检查的所需变量(A、C、G 和 T)。每当我在 char 中找到它时,我都会尝试基本上添加每个的数量。

感谢您的帮助!

最佳答案

发布的代码有很多问题,其中最大的问题是每次都会创建并返回一个新的 DNAnt。这将使计数方式比必要的更复杂,因为现在您必须计算 DNAnts。这里没有修复此代码,而是一种非常简单且愚蠢的不同方法:

std::map<char,int> DNACount;

创建一个将字符绑定(bind)到数字的对象。

DNACount[toupper(strand)]++;

如果还没有,这将为字符 strand 创建一个字符/数字对,并将数字设置为零。然后与strand配对的数字加1。

所以你所要做的就是通读序列,比如

std::map<char,int> DNACount;
for (char nucleotide:strand)// where strand is a string of nucleotide characters
{
DNACount[toupper(nucleotide)]++;
}
std::cout << "A count = " << DNACount['A'] << '\n';
std::cout << "C count = " << DNACount['C'] << '\n';
....

Documentation for std::map

关于c++ - 如何检查字符是否包含特定字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40965432/

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