首页 > 解决方案 > 关于使用子字符串而不必减去 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”

标签: javasubstring

解决方案


基本不包括结束索引 text.substring(0, length) 是从 0 到 length-1


推荐阅读