How to check if a char contains a specific letter

人走茶凉 提交于 2019-12-24 05:56:37

问题


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 desired output would be something like:

"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 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.

Thanks for the help!


回答1:


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)]++;

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

Documentation for std::map



来源:https://stackoverflow.com/questions/40965432/how-to-check-if-a-char-contains-a-specific-letter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!