Konstantine Tesla
Konstantine Tesla

Reputation: 17

Counting the occurrences of every char of of one string in another string

I am trying to write a function that takes two strings as arguments and returns the total count of how many times each character of the second string appears in the first.

For example, i = count("abracadabra", "bax"); would return 7.

I am looking to utilize the STL. I have written the following function that counts how many occurrences of one char happens in a string, but calling this function on a loop to solve the problem above seems quite inefficient.

int count(const std::string& str, char c)
{
    int count = 0;
    size_t pos = str.find_first_of(c);
    while (pos != std::string::npos)
    {
        count++;
        pos = str.find_first_of(c, pos + 1);
    }
    return count;
}

Upvotes: 1

Views: 111

Answers (1)

Inian
Inian

Reputation: 85550

You can modify the count function to accept a std::string as second argument and then loop one character at a time and use std::count to count the number of occurrences of each character and increment the overall count

#include <iostream>       // std::cout
#include <string>         // std::string
#include <algorithm>     // std::count

int count(const std::string& search, const std::string& pattern)
{
    int total = 0;
    for(auto &ch : pattern) {
        total += std::count(search.begin(), search.end(), ch);
    }

    return total ;
}

int main ()
{
    std::string hay("abracadabra");
    std::string needle("bax");

    std::cout << count(hay, needle) << std::endl;
    return 0;
}

Upvotes: 1

Related Questions