Write a function indexOf(source,sub) that takes two C++ strings and • returns -1
ID: 3629298 • Letter: W
Question
Write a function indexOf(source,sub) that takes two C++ strings and
• returns -1 if sub is not a substring in source
• returns the index of the first occurrence of sub in source (indices start at 0)
About the indexOf function
• make indexOf recursive
• do not use any built in library functions for strings (or for C-strings) except for the function length (http://www.cppreference.com/wiki/string/length)
• you may write your own helper functions
• do not allocate any memory in the function indexOf (nor when calling it) except for allocating an integer or two as local variables
• you may overload indexOf if you need extra parameters
Examples
indexOf("abcdefgh", "abc") returns 0
indexOf("abcdefgh", "ijklm") returns -1
indexOf("abc abc dbc", "dbc") returns 8
The main function, indexOf needs to be recursive, but this does not mean that there are no loops in any of the helper functions.
In your final version of the test program, read strings that are “a line long”. You can use either getline or cin.get to read in the strings (possibly with blanks) that you are going to pass on to indexOf.
Explanation / Answer
public static int indexOf(string sub, string source)
{
int l = source.length();
int pos = 0;
int start = source.indexOf(sub);
while(start != 1)
{
pos++;
start = source.indexOf(sub,source+l);
}
cout<<pos;
if(start == -1)
return -1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.