简体   繁体   English

c++ 计算字符数和出现时间

[英]Count number of characters and appear time in c++

Assume that i have an array of character contains a text message, example:假设我有一个包含文本消息的字符数组,例如:

"abccddcabbef"

Now i want to count the number of charracter and appear time of each character.现在我想计算每个字符的字符数和出现时间。 The result will be two arrays:结果将是两个数组:

char a[6] = {'a', 'b', 'c', 'd', 'e', 'f'}    // array of character
int b[6] = {2, 3, 3, 2, 1, 1}   // appear time

which is the best way to do this?这是最好的方法吗?

sorry about my english!对不起我的英语!

Why not do this: create an std::unordered_map , with its keys being the character and its values being an int.为什么不这样做:创建一个std::unordered_map ,它的键是字符,它的值是一个整数。

so for example:所以例如:

    unordered_map<char, int> map;
    string inputText;
    for (int i = 0; i < inputText.size(); ++i)
        {
           map[inputText[i]]++;
        }

Now you can iterate through this map, and you can find out the actual characters that you have seen so far as the map's keys, and the amount of times each character has appeared so far as the map's value.现在您可以遍历这个映射,并且可以找出到目前为止您看到的实际字符作为映射的键,以及到目前为止每个字符出现的次数作为映射的值。

Well, if the assumption is that the input string str is smaller than 128, then you know there are always going to be less than strlen(str) unique chars.好吧,如果假设输入字符串str小于 128,那么您知道总会有小于strlen(str)唯一字符。

Therefore you could do something like:因此,您可以执行以下操作:

std::string str = "abcabx";
char a[str.length()];
unsigned size[str.length()];

// zero arrays
memset(a, 0,  str.length());
memset(size, 0, str.length() * sizeof(unsigned));

unsigned num_unique = 0;
for (char x : str) {
  unsigned i = 0;
  while (a[i] != '\0' && a[i] != x) ++i;
  num_unique = std::max(i+1, num_unique);
  a[i] = x;
  ++size[i];
}

for (unsigned i = 0; i < num_unique; ++i) {
  std::cout << a[i] << " - " << size[i] << std::endl;
}

My answer is based on the assumption that you know the array lengths you will need for results in advance.我的回答是基于这样一个假设,即您事先知道获得结果所需的数组长度。 If you do not know that info in advance, I would suggest using List or ArrayList of char.如果您事先不知道该信息,我建议您使用字符的 List 或 ArrayList。

But, based on your question, this is what I would do.但是,根据您的问题,这就是我要做的。

int aCurrentIndex = 0;
for (i = 0; i  < origArray.length; i++) {
    if (!a.contains(origArray[i])) {
        a[aCurrentIndex] = origArray[i];
        b[aCurrentIndex] = 1;
        aCurrentIndex++;
    }
    else {
        b[a.indexOf(origArray[i])] = b[a.indexOf(origArray[i])] + 1;
    }
}

In the else statement, you might be able to use the following, but I haven't tested it, and don't want to tell you wrong.在 else 语句中,您可能可以使用以下内容,但我没有测试过,也不想告诉您错误。

b[a.indexOf(origArray[i])]++;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM