Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to count alphabetic character occurrences in a string with C++

2 Answers

0 votes
#include <iostream>
#include <string>
 
using std::cout;
using std::endl;
 
int main()
{
    int letters[26] = {0};
    std::string s = "c++ programming";
 
    for (int i = 0; i < s.length(); i++) {
        if (isalpha(s[i])) {
            letters[s[i] - 'a']++;
        }
    }
 
    for (int i = 0; i < 26; i++) {
        if (letters[i] != 0) {
            cout << (char)('a' + i) << ": " << letters[i] << endl;
        }
    }
}
 
 
 
/*
run:
 
a: 1
c: 1
g: 2
i: 1
m: 2
n: 1
o: 1
p: 1
r: 2

*/

 



answered Jun 13, 2018 by avibootz
edited Mar 2, 2025 by avibootz
0 votes
#include <iostream>
#include <cctype> 

void countLetterOccurrences(const char* str) {
    int counts[26] = {0}; // Array to store counts of each letter

    // Traverse the character array
    for (int i = 0; str[i] != '\0'; ++i) {
        if (std::isalpha(str[i])) { // Check if the character is a letter
            char lowerChar = std::tolower(str[i]); // Convert to lowercase
            counts[lowerChar - 'a']++; // Increment the count for the letter
        }
    }

    for (int i = 0; i < 26; ++i) {
        if (counts[i] > 0) {
            std::cout << static_cast<char>('a' + i) << ": " << counts[i] << std::endl;
        }
    }
}

int main() {
    const char* str = "C++ Programming";
    
    countLetterOccurrences(str);
}


/*
run:

a: 1
c: 1
g: 2
i: 1
m: 2
n: 1
o: 1
p: 1
r: 2

*/

 



answered Mar 2, 2025 by avibootz

Related questions

1 answer 202 views
1 answer 170 views
1 answer 130 views
1 answer 177 views
1 answer 173 views
...