获取字符串的第一个字符,直到字符串为空 ""

Taking the first Char of a String until the String is empty ""

我目前正在处理一项任务,我对 Substring 方法有疑问。 对于这个任务,我需要获取字符串的第一个字符,并在使用后删除第一个字符。

字符串是名称,最后我只想留下一个空字符串。

我的做法:

        String name = "Paul";
        char chr = name.charAt(0);
        String newName = name.substring(1);

我的问题:当我在最后一个字符“l”处使用我的子字符串时,我得到的是“”还是一个错误?

为确保没有错误,请执行以下操作。

String name = "Paul"; 
int nameLength = name.length();
for (int i = 0; i < nameLength; i++){ 
    char chr = name.charAt(0);
    if (i != nameLength - 1){
        String newName = name.substring(1);
        name = newName;
    } else {
        name = "";
    }
}

My questions: When I am at the last char "l" and use my substring do I get "" or an error?

您将得到一个空字符串。 documentation的以下几行中也提到了它:

Throws:

IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

当字符串中只剩下 l 时,它的长度将是 1,这是完全可以接受的 beginIndex。您也可以通过以下方式验证:

public class Main {
    public static void main(String[] args) {
        System.out.println("l".substring(1));
    }
}