How Do You Count The Occurrence Of A Given Character In A String?

Prashant | Wed, 03 Jun, 2020 | 332

How do you count the occurrence of a given character in a string?

How do we count the number of occurences of a character in a string, well as we know very well that string is widely asked in each and every interviews and many people do suffer with this.

So no need to worry now as we have brought so many questions now to study and learn,

Hashing is needed.

If you really want to go deep with this string question to count characters I will suggest you to learn Hashing as it is very well and efficient way to count occurance of any digit, characters or even strings.

We can discuss about hashing in later tutorials.

Basic approch to Count character.

Consider we have a string "SelfCode" now if we are asked to count the number of in the string then what is the basic approach for it ?

#include <bits/stdc++.h>
 
using namespace std;
int main(int argc, char** argv)
{
    string s="selfcode";
    int len=s.length();
    char ch='s'; // character to be searched 
    int count=0;
    for(int i=0;i<len;i++){
        if(s[i]==ch)
        count++;
    }
    
    cout<<count;
}

Hashing approach to solve the problem

Hashing approach is suitable when we have to find occurance of more than one character, so do not use it when you to find only single character.

So its good to learn with hashing too.

#include <bits/stdc++.h>
 
using namespace std;
int main(int argc, char** argv)
{
    string s="selfcode";
    int len=s.length();
    char ch='s'; // character to be searched 
    int hash[26]={0}; // setting array to be 0 
    for(int i=0;i<len;i++){
        hash[s[i]-'a']++;// to store position value using ascii value
    }
    
    cout<<hash[ch-'a'];
}

Hope you enjoyed it, do not forget to follow us on social media platforms.

0 comments
Leave a comment