Member-only story
In C++, create a method called findRun that finds the earliest occurrence in an array
of one or more consecutive strings that are equal to a target string
2 min readMay 2, 2022
Question
bool findRun(const string a[], int n, string target, int& begin, int& end);
Find the earliest occurrence in a
of one or more consecutive strings that are equal to target
; set begin
to the position of the first occurrence of target
, set end
to the last occurrence of target
in that earliest consecutive sequence, and return true. If n
is negative or if no string in a
is equal to target
, leave begin
and end
unchanged and return false. Here's an example:
string d[9] = {
"charlie", "november", "alpha", "alpha", "kilo", "kilo", "kilo", "alpha", "alpha"
};
int b;
int e;
bool b1 = findRun(d, 9, "alpha", b, e); // returns true and
// sets b to 2 and e to 3
bool b2 = findRun(d, 9, "november", b, e); // returns true and
// sets b to 1 and e to 1
bool b3 = findRun(d, 9, "sierra", b, e); // returns false and
// leaves b and e unchanged
Solution
bool findRun(const string a[], int n, string target, int& begin, int& end){bool foundTarget=false;for (unsigned int i=0; i<n; i++){cout << a[i] << endl;