【问题标题】:How to check if a char contains a specific letter如何检查字符是否包含特定字母
【发布时间】:2016-12-05 13:27:12
【问题描述】:

我正在尝试编写代码来检查一个 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 中找到它时,我基本上都会尝试添加每个的数量。

感谢您的帮助!

【问题讨论】:

  • 上次我检查时,char 足够大,正好可以容纳一个char。不多也不少。
  • 你的意思是,一个字符只能包含像“A”这样的字符?如果这就是 char 的工作方式,那么我想我需要稍微改变一下我的逻辑:P
  • 是的,char 就是这样。一个字符。不多也不少。
  • 你的意思是toupper,而不是isupper
  • 顺便说一句,单个字母的单引号,2个或更多字母的双引号。所以你的声明应该是"if (isupper(strand) == 'A')"。顺便说一句,您可以使用带有字符的switch;将strand 转换为大写,然后使用switch

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


【解决方案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

【讨论】:

    猜你喜欢
    • 2020-12-12
    • 2014-01-08
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 2011-07-11
    相关资源
    最近更新 更多