如何检查字符是否包含特定字母 [英] How to check if a char contains a specific letter

查看:112
本文介绍了如何检查字符是否包含特定字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试生成代码,以检查字符包含多少个 A, C, G和 T字符。但是我有点不确定如何去做..因为据我所知,没有像.contains()这样的运算符可以检查。

I'm trying to produce code that will check how many "A", "C", "G", and "T" characters a char contains. But I'm a little unsure how to go about doing this.. because as far as I know there aren't any operators like .contains() to check with.

所需的输出将类似于:

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

在我的代码中,我现在有以下内容:

In my code I have this right now:

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 is a structure that has the desired variables that I'm checking for (the A's, C's, G's and T's). And I'm trying to basically add to the amount of each whenever I find it inside of the char.

感谢您的帮助!

推荐答案

发布的代码存在很多问题,其中最大的问题是创建并返回了新的 DNAnt 每次。这将使计数方式变得不必要的复杂,因为现在您必须计数 DNAnts 。而不是修改此代码,这是一种非常简单而愚蠢的方法:

Lot of problems with the posted code, the biggest of which is a new DNAnt is created and returned every time. This will make the counting way more complicated than is necessary because now you have to count DNAnts. Instead of fixing this code, here's a really simple and stupid different way to do this:

std::map<char,int> DNACount;

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

creates an object that binds a character to a number.

DNACount[toupper(strand)]++;

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

If there isn't one already, this creates a character/number pairing for the character strand and sets the number to zero. Then the number paired with strand is increased by one.

因此,您要做的就是通读序列

So all you have to do is read through the sequence something like

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';
....

std :: map

这篇关于如何检查字符是否包含特定字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆