简体   繁体   中英

Determining the number of different characters

I have a really large file containing more than a million characters including spaces and newlines. I was able to find the number of occurrences of one character,

ifstream inData;
    inData.open("info.txt");
    char text;
    int achar=0;
    while (inData >> text)
    {
        if (text == 'a')
        {
            achar++;
        }

    }

    cout << achar;

I can expand this to all the characters but that will take more than 60 lines of code. At face value, using a for loop to span through the characters, appears to be a solution. However, the text isn't sorted so it will not work in the while loop. I attempted to insert the inData into a string. Once again, due to the fact that there are newlines it only took part of the text. So, I thought maybe using an array might help, but in light of the huge number of characters; it is not only hard to predict how many characters there are, but it also entails doing a loop more than a million times. Clearly, that isn't a wise route. Is there an effective way of doing this?

Just use an array for the counters:

int count[256] = {0};
unsigned char c;
while (inData >> c) {
    count[c]++;
}

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