CS U216 -- Algorithms and Data Structures for
Engineers
Assignment 3
Due 25 May, 2005
There are three parts to Assignment 3:
- Write a function that takes two arguments as inputs, both arguments of
type string. This function should return, as an int,
the number of times the first
argument appears as a substring in the second argument.
- Write a function that takes three arguments as inputs, the first two
arguments should be of type string, and the third of type int. The
function should return an int.
If n is the third argument, then the return value of this function
should be the location of the nth occurrence of the first argument
within the second argument as a substring.
By "location", I mean the index of the first character of the substring
within the second argument. For example, if the arguments are
("foo", "foobarfoo", 2), the result should be 6, because the second "foo"
is in character position 6.
If the substring does not appear within the string to search at
least n times, then the return value of the function should be -1.
If n is less than 1, then the function should return -2.
- Write a driver which allows a user to test the above two functions.
This driver should repeatedly ask the user whether there are more tests
to run.
If there are, then the program
should prompt the user for test inputs,
and then display the results of those tests for both functions,
with suitable wording.
An example interaction might look like this. You do not need to use the exact wording that appears here.
This is a driver for testing two substring functions.
Are there more tests to run? ?
I'm sorry, please answer with y or n.
Are there more tests to run? y
Please enter the substring to search for: abc
Please enter the string within which to search: abcdabcabe
Please enter which occurrence of that substring to find: 2
The substring occurs 2 times.
Occurrence 2 is at index 4.
Are there more tests to run? y
Please enter the substring to search for: abc
Please enter the string within which to search: abcdabcabe
Please enter which occurrence of that substring to find: 3
The substring occurs 2 times.
There is no occurrence 3.
Are there more tests to run? y
Please enter the substring to search for: who
Please enter the string within which to search: Who who's whose
Please enter which occurrence of that substring to find: 0
The substring occurs 2 times.
0 is not a legitimate occurrence argument.
Are there more tests to run? n
Last updated 24 May 2005.