如何在字符串中检测不同的字母和数字

How to detect different letters and numbers in a string

本文关键字:数字 字符串 检测      更新时间:2023-10-16

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

尝试解决这个问题时,我试图拿每个字母和数字,然后将它们置于动态数组中。这样,我就可以对数组进行排序,然后计算每个字母和数字出现多少次。但是问题在于,有太多可能的结果可供选择,因此我无法手动分类每个角色。除此之外,我不知道如何在数组中使用这些项目,并将其与一段时间循环相关。

所以这是我到目前为止的独立片段...

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

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

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

您可以在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;

live

字符集有多大?如果简单的ASCII,则可以创建256个值的数组,请在0。

的所有值中启动所有值。

然后:

for each(character in string){
    myCountArray[character]++;
}

这无法与巨大的角色集合。