在了解起始索引和子字符串的工作原理方面几乎不需要帮助
Need little help on understanding how starting index and substring works
这是我的代码
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type a word: ");
String userWord = reader.nextLine();
System.out.print("Length of the first part: ");
int userLength = Integer.parseInt(reader.nextLine());
System.out.println("Result: " + userWord.substring(0, userLength));
}
结果:
Type a word: hellothere
Length of the first part: 3
Result: hel
起始索引是从0开始计数对吧?那么结果不应该打印"hell"吗?
0 = h
1 = e
2 = l
3 = l
substring()
的第二个参数是独占索引。意思是:当你输入 3 时,它只会给你直到索引 2 的字母。这不是 Java API 中最明显的方法之一,但应该有很好的记录。
这是我的代码
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type a word: ");
String userWord = reader.nextLine();
System.out.print("Length of the first part: ");
int userLength = Integer.parseInt(reader.nextLine());
System.out.println("Result: " + userWord.substring(0, userLength));
}
结果:
Type a word: hellothere
Length of the first part: 3
Result: hel
起始索引是从0开始计数对吧?那么结果不应该打印"hell"吗?
0 = h
1 = e
2 = l
3 = l
substring()
的第二个参数是独占索引。意思是:当你输入 3 时,它只会给你直到索引 2 的字母。这不是 Java API 中最明显的方法之一,但应该有很好的记录。