Most efficient way to get substring not exceeding the length of the string

I am currently trying to convert a string to a digit with this code:

public static int getDigit(String whole, int sub) {
    int d = Integer.parseInt(whole.substring(sub, sub+1));
    print(Integer.toString(d));

    return d;
}

      

But when I try to get the last digit, I run into an error, I know the reason, but is there a way to overcome this, like an algorithm (efficient method) that accomplishes this, other than my example:

public static int getDigit(String whole, int sub) {
    int d = 0;

    if (sub < whole.length())
        d = Integer.parseInt(whole.substring(sub, sub+1));
    else
        d = Integer.parseInt(whole.substring(sub));
    print(Integer.toString(d));

    return d;
}

      

NOTE. Please ignore any errors in your code as I have not tested the second example. The first example obviously has bugs.

+3


source to share


1 answer


An alternative (assuming you are expecting one character as a "digit") would process the character at the passed in index by pulling char

and converting it to int

.

This can be done using a method getNumericValue(char ch)

from the character class .



int d = Character.getNumericValue(whole.charAt(sub));

      

+3


source







All Articles