Confused on how to do this one. Can someone show me their code and JavaDoc it to
ID: 3869710 • Letter: C
Question
Confused on how to do this one. Can someone show me their code and JavaDoc it to help me understand it better please. I am using Eclipse to code (Java). Thanks!
For this problem, Substring, you will write your own modified version of the substring method. The method signature is:
public static String substring(String string, int startIndex, int endIndex);
The method should return a new string that is a substring of the string given as input parameter and starts at startIndex (inclusive) and ends at endIndex (exclusive). You are not allowed to use methods from the String library besides .length() and .charAt().
Explanation / Answer
Here is the code for you:
import java.util.*;
class SubstringExtraction
{
//The method should return a new string that is a substring of the string given as
//input parameter and starts at startIndex (inclusive) and ends at endIndex (exclusive).
//You are not allowed to use methods from the String library besides .length() and .charAt().
public static String substring(String string, int startIndex, int endIndex)
{
int stringLength = string.length();
//If the array indices are out of bounds, return null.
if(startIndex < 0 || endIndex < 0 || startIndex >= stringLength || endIndex > stringLength)
return null;
String temp = "";
//Starting from startIndex, upto endIndex copy each character into temp.
for(int i = startIndex; i < endIndex; i++)
temp += string.charAt(i);
return temp; //Finally return temp.
}
}