Member-only story

In C++, write a method called findMatch that returns the position of a string in the array that is equal to target

Marika Lam
1 min readMay 2, 2022

int findMatch(const string a[], int n, string target);

Return the position of a string in the array that is equal to target; if there is more than one such string, return the smallest position number of such a matching string. Return −1 if there is no such string.

string d[9] = {
"charlie", "novembe", "alpha", "alpha", "kilo", "kilo", "kilo", "alpha", "alpha"
};
int m = findMatch(d, 9, "kilo"); // returns 4
int p = findMatch(d, 4, "kilo"); // returns -1 (no "kilo" in first 4)

Solution

int findMatch(const string a[], int n, string target){int findFirstMatchPosition = 0;for(unsigned int i = 0; i < n; i++){if (a[i]==target){findFirstMatchPosition=i;break;}}if (findFirstMatchPosition == 0){return -1;} else {return findFirstMatchPosition;}}

Explanation

Iterate through the array and find if a[i] equals to the target string, add the position to the variable findFirstMatchPosition and break out of the for loop. Once outside the for loop, return -1 if there were no matches, else return the position of the first found string in the array.

--

--

No responses yet