82.5k views
2 votes
CSC 191

Lab 8 - Recursion with Strings
Due Date: 3/22/2023
Write and implement the following recursive methods:
1. boolean isDup1icate(String s): check if the 2nd half of s is a copy of the 1st half. For example, return true for s= "abcabc" or s= "abcdabc", and return false for s= "abcdef".
2. int evalAS1(String e): evaluate expression e consisting of only single-digit operands and,+ - operators. An example of a valid expression e would be 5+6-3, which should return 8 .
3. int indexof(String s1, String s2 ): find the position of s2 on s1. Return the leftmost location if s2 appears multiple times on s1, and return -1 if s2 is not found on s1.
You are not allowed to use built-in methods . indexof() or . Tastindexof() here. Your main program should use an appropriate menu to test the methods above.
Name your file FirstnameLastnameLab8.java.
Additional Assignment Requirements 1. Your methods must use recursion.

1 Answer

3 votes

Final answer:

This answer provides a step-by-step explanation of how to implement the required recursive methods for Lab 8, including checking for duplicates in a string, evaluating arithmetic expressions with single-digit operands and operators, and finding the index of a substring in a string.

Step-by-step explanation:

1. boolean duplicate(String s):

To check if the 2nd half of string s is a copy of the 1st half, we can use recursion by comparing the characters at corresponding positions in the two halves. If the characters don't match, we return false. If the lengths of the two halves become 0, we return true as all characters in the halves have been successfully compared.

2. int evalAS1(String e):

To evaluate the arithmetic expression e, we can use recursion by splitting the expression into two parts: the left operand and the right operand. We can recursively evaluate the left operand and the right operand, and then perform the appropriate operation based on the operator in the middle.

3. int index of(String s1, String s2):

To find the leftmost position of string s2 in string s1, we can use recursion by checking if the first character of s2 matches the first character of s1. If so, we recursively compare the remaining characters of s1 and s2. If not, we recursively search for s2 in the remaining characters of s1.

User Treborbob
by
7.9k points