Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Check whether two characters present equally in a given string

C++ String: Exercise-9 with Solution

Write a C++ program to check whether two characters present equally in a given string.

Pictorial Presentation:

C++ Exercises: Check whether two characters present equally in a given string

Sample Solution:

C++ Code :

#include <iostream>
#include <string>

using namespace std;

string count_chars(string str, string chr1, string chr2) {

	int ctr1 = 0, ctr2 = 0;

	for (int x = 0; x < str.length(); x++)
	{
		if (str[x] == chr1[0])
			ctr1++;

		if (str[x] == chr2[0])
			ctr2++;
	}

	if (ctr1 == ctr2)
	{
		return "True";
	}
	else
	{
		return "False";
	}
}

int main() {

	cout << count_chars("aabcdeef","a","e") << endl; // true
    cout << "\n" << count_chars("aabcdef","a","e") << endl; //false
    cout << "\n" << count_chars("aab11cde22f","1","2") << endl; //true
	return 0;
}

Sample Output:

True

False

True

Flowchart:

Flowchart: Check whether two characters present equally in a given string.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to count all the words in a given string.
Next: Write a C++ program to check if a given string is a Palindrome or not.

What is the difficulty level of this exercise?