Member-only story
In C++, write a method called enumerate that returns the number of strings in the array that are equal to the target string
1 min readMay 2, 2022
Question
int enumerate(const string a[], int n, string target);
Return the number of strings in the array that are equal to target
. If n
is negative, the function returns −1.
string d[9] = {
"charlie", "november", "alpha", "alpha", "kilo", "kilo", "kilo", "alpha", "alpha"
};
int i = enumerate(d, 9, "alpha"); // returns 4
int j = enumerate(d, 5, "kilo"); // returns 1
int k = enumerate(d, 9, "bravo"); // returns 0
Solution
int enumerate(const string a[], int n, string target){int countMatchingStrings = 0;for(unsigned int i = 0; i < n; i++){if (a[i]==target){countMatchingStrings++;}}//if found none, return 0if (countMatchingStrings == 0){return 0;} else {return countMatchingStrings;}}
Explanation
Declare a counter outside of the for loop that will increase by 1 whenever the target string has been found inside the array. If the target string is found in the iteration, add 1 to the counter. Once the for loop has been finished iterating, return 0 if the countMatchingStrings equals to 0, else return the number of matches found in the array.