如何检查char是否包含特定字母

时间:2016-12-05 00:29:16

标签: c++ struct char structure c-strings

我正在尝试生成代码,用于检查char包含多少“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中找到它时,我都会尝试基本上添加每个数量。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

发布的代码存在很多问题,其中最大的问题是新的DNAnt,每次都会创建并返回。这将使计数方式变得更加复杂,因为现在你需要计算DNAnts。而不是修复此代码,这是一个非常简单和愚蠢的不同方式:

std::map<char,int> DNACount;

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

DNACount[toupper(strand)]++;

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

所以你要做的就是阅读像

这样的序列
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

相关问题