首页 > 解决方案 > 如何检测字符串中的不同字母和数字

问题描述

因此,假设其中有一串随机且不同的字母和数字,例如"7GGG66HH". 我试图找出一种方法来检测该字符串中包含的每个单独的数字和字母,并输出一个列表,显示每个字母或数字有多少种类型。

在尝试解决这个问题时,我尝试获取每个单独的字母和数字,并将它们放入一个动态数组中。这样我就可以对数组进行排序并计算每个字母和数字出现的次数。但问题是有太多可能的结果可供选择,所以我无法手动对每个单独的字符进行排序。除此之外,我不知道如何处理数组中的项目,并将其与 while 循环关联使用。

所以这是我到目前为止的一个单独的片段......

int main()
{
  string userInput;
  cin >> userInput;

  vector<string> arrayOfCharacters(0);

  int x = 0;

  while (x < lastElemetOfTheArray)
  {
    // tally up the number of each letter and number present

    ++x;
  }

  // display the number of times each letter and number was present

  return 0;
}

假设您输入 5AAY00UUU

预期的输出将是

15
2A
1Y
20
3U

注意第一个数字是该字符出现的次数。

另外,我想知道我是否通过使用 while 循环和动态数组来思考正确的方向。如果有完全不同的解决方案,或者我使用的方法不正确,请告诉我。谢谢!

标签: c++

解决方案


您可以借助std::map. 例如

// define a map, key is the character, mapped value is used for counting
std::map<char, int> m;

// increase the count on every character
// if key does not already exist, std::map::operator[] would insert one with mapped value initialized as 0
for (auto c : userInput)
    m[c]++;

// print out the result
for (auto const& p : m)
    std::cout << p.second << p.first << std::endl;

居住


推荐阅读