How can I fix this code so the function countChars accepts a character as parameter?

I'm not really sure what my professor wants this character to do? This is the instructions: Write a function (countChars) that accepts a string and a character as parameters. Returns the number of times the character appears in the string
Check for anagram using the following steps
Assume you have two strings – A and B
If A is not the same length as B, not anagrams
Convert A and B to all lower case.
For each letter in A, call your countChar on A and B. If the results do not match, stop
If each letter in A returns the same number in B, then they are anagrams.
And this is what i have so far, please let me know if you understand what my professor wants me to do with this character and if you see any other errors. Thanks!~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include<iostream>
#include<string>
#include<algorithm>

using namespace std;

int countChars(string a, string b, char c) {
sort(a.begin(), a.end());
sort(b.begin(), b.end());
if (a == b) {
	return true;
}
else {
	return false;
}
}

int main() {
	string a, b;

	cout << "Enter a word: " << endl;
	cin >> a;
	cout << "Enter another word: " << endl;
	cin >> b;

	if (true)
	{
		cout << "They are anagrams of each other." << endl;
	}
	else
	{
		cout << "They are not anagrams of each other." << endl;
	}
	return 0;
}
amm123 wrote:
Write a function (countChars) that accepts a string and a character as parameters. Returns the number of times the character appears in the string
Here is an example usage:

int times = countChars("Hello, World!", 'l');

After this line, times would have the value 3
Last edited on


1
2
3
4
5
6
7
8
9
10
11
12
13
14
bool isAnagram(string a, string b) {
    // convert all characters in a to lowercase
    // convert all characters in b to lowercase
    // http://stackoverflow.com/questions/313970/how-to-convert-stdstring-to-lower-case

    For each c in a do:
        If countCharacters(b, c) /= countCharacters(a, c) then
            Return False
        End If
    End Loop
    Return True

    // http://stackoverflow.com/questions/18267407/check-whether-two-strings-are-anagrams-c
}

Smac89 I understand most of what you said. only I'm unsure what to make my last do while loop do. I know I'm supposed to have a statement for it to 'do' but I don't get what I would put there. heres what i have:

1
2
3
4
5
6
7
8
do {
	if (countChars(b, c) /= countChars(a, c) {
		return false;
	}
	else {
		return true;
	}
} while
Topic archived. No new replies allowed.