Implementing unusual string operations.
In this assignment, you’ll implement and test a method that extracts a substring of a specified string, and (optionally) reverses it.
In the edu.cnm.deepdive.StringWarp
class, the substring
method is declared with the following signature, return type, and modifiers:
public static String substring(String input, int beginIndex, int endIndex) throws IndexOutOfBoundsException
The implementation must not change the modifiers, return type, method name, parameter types/number/order, or possible exceptions shown above. For more method declaration details, see the Javadoc documentation.
When (beginIndex <= endIndex)
, StringWarp.substring(input, beginIndex, endIndex)
must return the same result as input.substring(beginIndex, endIndex)
(i.e. it must behave exactly like the substring
method of the String
class).
When (beginIndex > endIndex)
, StringWarp.substring(input, beginIndex, endIndex)
must return the reverse of the result returned by input.substring(endIndex, beginIndex)
.
Any StringIndexOutOfBoundsException
that would be thrown by String.substring
must also be thrown by this implementation.
For example, the code fragment
StringWarp.substring("Kotlin", 1, 5)
must return
"otli"
However,
StringWarp.substring("Kotlin", 5, 1);
must return
"ilto"
Note that the second output string is the same is the first, but reversed.
You may find it useful to create one or more additional static
methods as “helpers”; the problem can be solved without doing so, however.
Do not hesitate to declare any constants (static final
fields) that you feel might simplify or clarify your code.
There are several ways to reverse a string. Feel free to use any approach that makes sense to you—and don’t forget to investigate the use of classes in the Java standard library—such as StringBuilder
—that support construction and manipulation of mutable character sequences.
If you leverage the String.substring
(or StringBuilder.substring
) method as much as possible in your code, there should be no need for you to write any logic to detect exceptional conditions.
The method to be completed includes a TODO
comment to that effect.
The StringWarp.substring
implementation will be verified using these test cases:
input |
beginIndex |
endIndex |
Expected return value | Expected exception |
---|---|---|---|---|
"bootcamp" |
2 |
6 |
"otca" |
N/A |
"bootcamp" |
6 |
2 |
"acto" |
N/A |
"bootcamp" |
3 |
3 |
"" |
N/A |
"algorithm" |
0 |
9 |
"algorithm" |
N/A |
"algorithm" |
9 |
0 |
"mhtirogla" |
N/A |
"bootcamp" |
-1 |
0 |
N/A | StringIndexOutOfBoundsException |
"bootcamp" |
0 |
-1 |
N/A | StringIndexOutOfBoundsException |
"bootcamp" |
0 |
9 |
N/A | StringIndexOutOfBoundsException |
"bootcamp" |
9 |
0 |
N/A | StringIndexOutOfBoundsException |