在不超过字符串长度的情况下获取子字符串的最有效方法

Most efficient way to get a substring without exceeding the string length

我目前正在尝试使用以下代码将字符串转换为数字:

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

    return d;
}

但是当我尝试获取最后一位数字时 运行 出错了,我知道原因但是有没有办法克服这个问题,比如执行这个而不是我的算法(有效方法)此处示例:

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;
}

注意:请忽略代码中的任何错误,因为我还没有测试第二个示例。第一个例子明显有错误

另一种方法(假设您期望单个字符作为 'digit')将通过拉动 char 并将其转换为 [=12] 来处理传递的索引处的字符=].

这可以通过 Character class 中的 getNumericValue(char ch) 方法来完成。

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