0

create a program that counts the number of occurence of an alphabet character counting letters in a string in c++

I have come across different codes but nothing is good to our professor, my professor wanted only #include <iostream> , #include<conio.h>, using namespace std;,letters that have been type by user is the letter that prints or outcomes

maybe this can help, here is my professor's previous code:

    for(int y=0; y<=9; y++){
        int counter=0;
        for (int x=0; x<=99;x++){
            if (refchar[y]==userchar[x]){
                counter++;
            }
        }
        cout<<refchar[y]<<"="<<counter <<"\n";
    }  
    getch();
    return 0;  
}

And here is my code :

int main(){
    string refchar="char alphabet[26]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
                    'O','P','Q','R','S','T','U','V','W','X','Y','Z'};
";
    char userchar[500]="";
    cout<<"Enter number:";
    cin>>userchar;

    for(int y=0; y<=9; y++){
        int counter=0;
        for (int x=0; x<=99;x++){
            if (refchar[y]==userchar[x]){
                counter++;
            }
        }
        cout<<refchar[y]<<"="<<counter <<"\n";
    }  
    getch();
    return 0;  
}
Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56
  • Have you compiled and seen what does your program does currently? – P.W Sep 19 '18 at 04:33
  • `std::isalpha` ? https://en.cppreference.com/w/cpp/string/byte/isalpha . If you are not allowed to use `std::alpha`, why dont you look at ASCII table and decide based on ASCII number. – macroland Sep 19 '18 at 05:21
  • Fire up your debugger and step through the code line by line. Inspect the flow of control as well as variable values along the way. – Jesper Juhl Sep 19 '18 at 05:24
  • 1
    Please, note, that proper indentation is completely ignored by the compiler but helps the human reader much to recognize the structure of code. I improved the indentation of your sample code a bit. Btw. there is a `";` in `main()` which would cause a syntax error. It's probably an "accidental artefact". – Scheff's Cat Sep 19 '18 at 05:26
  • @macroland If you're going to compare the characters using their encoding value, use the character literals like `'A'`, instead of the ASCII values. There is absolutely no reason to write the ASCII values, and all it does is make the code harder to read and also dependent on ASCII being used in the first place, which is not guaranteed by the standard. – eesiraed Sep 19 '18 at 23:14
  • @FeiXiang: If you are dealing with ASCII character sets and that you know in a certain consecutive range it is capital and in a certain consecutive range it is small, "I think" the code will be simpler and easier to read with just a single line of comment. – macroland Sep 20 '18 at 00:30
  • @macroland I meant that you should write `if (c >= 'A' && c <= 'Z')` instead of `if (c >= 65 && c <= 90)`. The former is much more readable, and doesn't rely on ASCII being used. `std::isalpha` is still the best option though. – eesiraed Sep 21 '18 at 01:07

4 Answers4

0

To count occurrences of a char in a string you can simply do something like this:

std::map<char, int> occurrences;
for (const auto& character : the_string) {
    occurrences[character]++;
}

Now every possible char can be looked up/used as a key in the occurrences map and the value will be the count of that character.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • I wanted to write something similar to this too. but he mentioned ` professor wanted only #include , #include, using namespace std;`, so you need to change this code to wihtout using map. – Afshin Sep 19 '18 at 05:31
0

Even though this is not a good code, you asked for something with only those 3 headers, so I wrote code like this:

#include <iostream>
using namespace std;

int main() {
    char userchar[500]="";
    cin.getline(userchar, sizeof userchar);
    int charscnt[128] = {0,};
    int idx = 0;

    while (userchar[idx] != 0) {
        charscnt[static_cast<int>(userchar[idx])]++;
        idx++;
    }

    for (int i = 0; i < sizeof charscnt / sizeof(int); i++) {
        if (charscnt[i] != 0) {
            cout << static_cast<unsigned char>(i) << "=" << charscnt[i] << endl;
        }
    }

    return 0;  
}

Logic is similar to using map that is mentioned by Jasper, but I used a small array to simulate map.

Afshin
  • 8,839
  • 1
  • 18
  • 53
0

Without using string processing commands from string.h and stdlib.h, once can still do this by stepping through the string byte-by-byte until the terminating '\0' byte is found.

Of course we're also assuming a simple 1 letter = 1 byte set of characters too. It's typically more complicated than that and you may need to handle multi-byte letters etc.

#include <iostream>
const int ALPHABET_SIZE = 256;  // maximum size of iso-8859-1 / ASCII

int main(int argc, char **argv)
{
    int i;
    const char *input="Some input string to search";   // string to process
    unsigned int counts[ALPHABET_SIZE];         // used to tally found letters

    // initialise the count table
    for (i=0; i<ALPHABET_SIZE ; i++)
        counts[i] = 0;

    // c-strings are terminated with a '\0' character
    // step through each character, tallying it up
    const char *ptr = input;
    while (*ptr != '\0')
    {
        int letter_num = (int)(*ptr);  // a letter is just a number
        counts[letter_num] += 1;
        ptr += 1;
    }

    // print the count table
    for (i=0; i<ALPHABET_SIZE ; i++)
    {
        // if we have that letter
        if (counts[i] > 0)
            std::cout << (char)i << " => " << counts[i] << "\n";
    }

    return 0; // all is ok
}
Kingsley
  • 14,398
  • 5
  • 31
  • 53
  • You don't need to set counts array to 0 at the beginning (like `C`) because *All array elements that are not initialized explicitly are initialized implicitly the same way as objects that have static storage duration. * – Afshin Sep 19 '18 at 06:04
  • @Afshin - I'm not sure that's true, see: https://stackoverflow.com/questions/2218254/variable-initialization-in-c POD types are not initiialised for C compatibility reasons, array types are not either, unless initialisation syntax (e.g. x[] = {}) is used - which I didn't. – Kingsley Sep 19 '18 at 06:19
0

The best one liner is to use the std::count

Check out the self explanatory code:

#include <iostream>
#include <algorithm>
#include <string>

int main()
{
    std::string s = "Hi How Are You Doing ?";
    size_t n = std::count(s.begin(), s.end(), ' ');
    std::cout << n;
}
Rishi
  • 64
  • 4