w3resource

C++ String Exercises: Count occurrences of a certain character in a string

C++ String: Exercise-37 with Solution

Write a C++ program that counts the number of instances of a certain character in a given string.

Test Data:
("Exercises", "e") -> 2
("Compilation Time", "i") -> 3

Sample Solution:

C++ Code:

#include <bits/stdc++.h>

using namespace std;

int test(string s, char c)
{
    int res = 0;
    for (int i=0;i<s.length();i++)
        if (s[i] == c)
            res++;
    return res;
}

int main()
{
	string str = "Exercises";
	char ch ='e';
	cout << "String: " << str;
	cout << "\nCharacter: " << ch;
	cout << "\nCount occurrences of '" << ch << "' in '" << str << "': " << test(str, ch) << endl; 
	str = "Compilation Time";
	ch ='i';
	cout << "\nString: " << str;
	cout << "\nCharacter: " << ch;
	cout << "\nCount occurrences of '" << ch << "' in '" << str << "': " << test(str, ch) << endl; 
}

Sample Output:

String: Exercises
Character: e
Count occurrences of 'e' in 'Exercises': 2

String: Compilation Time
Character: i
Count occurrences of 'i' in 'Compilation Time': 3

Flowchart:

Flowchart: Count occurrences of a certain character in a string.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous C++ Exercise: Check two consecutive, identical letters in a word.

Next C++ Exercise: Remove a specific character from a given string.

What is the difficulty level of this exercise?



Share this Tutorial / Exercise on : Facebook and Twitter

C++ Programming: Tips of the Day

How to replace all occurrences of a character in string?

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}

Ref: https://bit.ly/3niU71x