C ++阅读句子

时间:2018-09-27 05:46:22

标签: c++

字符串a = MwZwXxZwDwJrBxHrHxMrGrJrGwHxMrFrZrZrDrKwZxLrZrFwZxErMrXxArZw;

假设我的字符串中有此数据。我想用字符串记录多少M,Z,X,D,J(包括我没有提到的大写字母)怎么做?我的朋友说使用vector可以做到,但是我真的不知道如何使用vector还有其他替代方法。

我尝试使用for循环进行操作并找到M,然后将指针重置为0以继续查找下一个大写值,但不确定是否有更简单的方法来实现。

3 个答案:

答案 0 :(得分:0)

首先,我将向您展示一种“更轻松”的方式。

#include <iostream>
#include <map>

using namespace std;

int main(int argc, const char * argv[]) {
    string str = "MwZwXxZwDwJrBxHrHxMrGrJrGwHxMrFrZrZrDrKwZxLrZrFwZxErMrXxArZw";
    map<char,int> map;

    for (int i=0; i<str.length(); i++) {
        char ch = str[i];

        if (isupper(ch)) {
            map[ch] ++;
        }
    }

    for (auto item : map) {
        cout<<item.first<<':'<<item.second<<endl;
    }

    return 0;
}

您只需使用1个循环即可解决您的问题。

'isupper(int _c)'是标准库中的函数,它可以告诉您字符是否为大写字母。

“地图”也是标准库中的数据结构,它可以为您做键值存储。

该程序输出以下内容:

A:1
B:1
D:2
E:1
F:2
G:2
H:3
J:2
K:1
L:1
M:4
X:2
Z:8

这是你想要的吗?

答案 1 :(得分:0)

使用正则表达式。

using namespace std;
// regex_search example
#include <iostream>
#include <string>
#include <regex>

int main ()
{
  std::string s ("MwZwXxZwDwJrBxHrHxMrGrJrGwHxMrFrZrZrDrKwZxLrZrFwZxErMrXxArZw;");
  std::smatch m;
  std::regex e ("[A-Z\s]+");
  map<string,int> map;

  std::cout << "Target sequence: " << s << std::endl;
  std::cout << "Regular expression: [A-Z\s]+" << std::endl;
  std::cout << "The following matches and submatches were found:" << std::endl;

  while (std::regex_search (s,m,e)) {
    for (auto x:m)
    {
        //cout << x << " ";
        map[x.str()] ++;
    }
    //cout << std::endl;

    s = m.suffix().str();
  }
  for (auto item : map) {
          cout<<item.first<<':'<<item.second<<endl;
      }
  return 0;
}

答案 2 :(得分:0)

“循环遍历字符串并计算大写字母”到C ++的最直接翻译是:

#include <iostream>
#include <map>
#include <cctype>

int main()
{
    string a = "MwZwXxZwDwJrBxHrHxMrGrJrGwHxMrFrZrZrDrKwZxLrZrFwZxErMrXxArZw";
    std::map<char, int> count;

    // Loop through the string...
    for (auto c: a)
    {
        // ... and count the uppercase letters.
        if (std::isupper(c))
        {
            count[c] += 1;
        }
    }

    // Show the result.
    for (auto it: count)
    {
        std::cout << it.first << ": " << it.second << std::endl;
    }
}