java - 关于使用子字符串而不必减去 1 的问题
问题描述
创建一个打印单词第一部分的程序。程序询问用户单词和第一部分的长度。在程序中使用 substring 方法。https://puu.sh/EqqmC/231457edec.png
下面的代码提供了正确的答案,但我想知道为什么不需要从长度中减去 1 来生成具有正确字符数的单词。即)如果 String word 是“example”并且长度 int 是 4,则返回值是“exam”,但是如果从 0 开始计数,则结果应该是“examp”
返回 text.substring(0, 长度);
import java.util.Scanner;
public class FirstPart {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a word: ");
String word = reader.nextLine();
System.out.println("Length of the first part: ");
int length = Integer.parseInt(reader.nextLine());
System.out.println("Result: " + firstPart(word, length));
}
// prints the first part of the word
public static String firstPart(String text, int length) {
return text.substring(0, length);
}
}
如果 String word 为“example”且长度 int 为 4,则返回值为“exam”
解决方案
基本不包括结束索引 text.substring(0, length) 是从 0 到 length-1
推荐阅读
- git - 公众可以查看之前 GitHub 推送的内容吗?
- unity3d - 有没有办法定位 NavMesh 对撞机
- regex - 从长字符串列创建布尔列。多选题
- python - 如何使用 python boto3 获取 AWS 的 S3(所有存储桶)中每个对象的大小
- git - 更改整个 git 分支历史以匹配另一个分支的历史
- c++ - “std::transform”在多个编译器上编译时没有限定名称查找?
- python - IndexError:只有整数、切片(`:`)
- c++ - [C++]即使自第一次声明以来从未分配过变量,值也已更改
- c# - 如何将 aa Xamarin.IOS 类库导入 Xcode ObjC?
- rxjs - 可观察的流 - 一对多 vs 多对一