logo CodeStepByStep logo


Language/Type: C++ recursion string return
Related Links:
Author: Marty Stepp (on 2016/08/27)

Write a recursive function named nonMatching that accepts two strings as parameters, and returns an integer representing the number of character indexes between the two strings that do not match. For this problem, two strings are defined as having a "match" at a given index if they contain exactly the same ASCII character value at that index. For example, consider the following two strings:

// index     012345678901234
string s1 = "I love Mariana!";
string s2 = "U Love Marty";

In the above example, seven indexes do not match (underlined above for emphasis): indexes 0, 2, 10, 11, 12, 13, and 14. So the call of nonMatching(s1, s2) would return 7 . Any character could match or fail to match, including letters, numbers, spacing, punctuation, etc. Your function is case-sensitive; notice that the 'l' and 'L' at index 2 do not match.

If the two strings are not the same length, any indexes at the end of the longer string by definition do not match, since there is no character in the other string at that index that could correspond to them. One implication of this is that if one of the parameters is an empty string, the entirety of the other string is considered non-matching.


  • Do not use any loops; you must use recursion.
  • Do not declare any global variables.
  • Do not call any string member functions or string library functions that traverse or search the entire string. Some examples of such functions are: find, rfind, stringIndexOf, stringContains, replace, stringSplit, etc. (The point of this problem is to solve it recursively; do not use a library function to get around recursion.)
  • Do not use any auxiliary data structures like Vector, Map, Set, arrays, etc. You can declare as many primitive variables like ints as you like, as well as strings.
  • You are allowed to define other "helper" functions if you like; they are subject to these same constraints.
Type your solution here:

This is a function problem. Write a C++ function as described. Do not write a complete program; just the function(s) above.

You must log in before you can solve this problem.

Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.

© Marty Stepp, all rights reserved.