logo CodeStepByStep logo

IndexOf

Language/Type: C# recursion string return
Related Links:

Write a recursive method named IndexOf that accepts two strings s1 and s2 as parameters and that returns the starting index of the first occurrence of the second string s2 inside the first string s1, or -1 if s2 is not found in s1. The table below shows several calls to your method and their expected return values. If s2 is the empty string, always return 0 regardless of the contents of s1. If s2 is longer than s1, it of course cannot be contained in s1 and therefore your method would return -1 in such a case. Notice that case matters; the last example returns -1.

Call Value Returned
IndexOf("Barack Obama", "Bar") 0
IndexOf("foo", "foo") 0
IndexOf("Stanford CS", "ford") 4
IndexOf("Barack Obama", "ack") 3
IndexOf("Barack Obama", "a") 1
IndexOf("sandwich", "") 0
IndexOf("Barack Obama", "McCain") -1
IndexOf("Barack Obama", "ACK") -1

Constraints: Your solution must obey the following constraints:

  • Your solution must not use any loops; it must be recursive.
  • strings have member methods named find and rfind, but you should not call them, because they allow you to get around using recursion. Similarly, the replace member is forbidden. You should limit yourself to using only the following string members:
    • at, append, compare, erase, insert, length or size, substr, trim, operators such as [], ==, !=, <, etc.
  • Do not construct any data structures (no array, list, set, map, etc.), and do not declare any global variables. You are allowed to define other "helper" methods if you like.
Method: Write a C# method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.