简体   繁体   中英

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.

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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