171k views
0 votes
Write a function int count_foobar_chars(std::string str) that returns the number of foobar characters. The foobar characters are the letters f,0,b,a,r, and their uppercase variants because they form the word "foobar". Write a helper function bool is_foobar_char(std: :string s) that checks whether a character is a foobar char, and use it in count_foobar_chars ().

1 Answer

1 vote

Final answer:

The question is about writing a C++ function to count the number of specific characters in a string. The functions include a helper function to check if a character is one of the 'foobar' characters and a counting function that leverages this check.

Step-by-step explanation:

The student has asked for help writing a function in C++ that counts the number of certain characters in a string. The characters of interest are those that make up the word "foobar" (f, o, b, a, r), including their uppercase variants. Here are the functions that fulfill this requirement:

bool is_foobar_char(char c) {
std::string foobar_chars = "fFoObBaArR";
return foobar_chars.find(c) != std::string::npos;
}

int count_foobar_chars(std::string str) {
int count = 0;
for (char c : str) {
if (is_foobar_char(c)) {
count++;
}
}
return count;
}

The is_foobar_char function checks whether a given character is one of the foobar characters. The count_foobar_chars function then uses this helper function to iterate through the given string and count the occurrences of foobar characters.

User Jakejgordon
by
8.8k points