首页 > 解决方案 > 返回从 String 的输入参数索引开始的字符串

问题描述

标签: javafor-loopreturnsubstringstring-length

解决方案


return 语句由类似于 if-else 条件的三元条件组成。如果索引大于字符串的长度,它将返回“”,否则它将从输入索引返回子字符串

public class Test {
    public static void main(String[] args) {
        System.out.println("String that begins at 2 index : "+getTheString(2)); // Output waii
        System.out.println("String that begins at 8 index : "+getTheString(8));// Output ""
    }

    public static String getTheString(int index) {

        String str = "Hawaii";

        return index > str.length() ? "" : str.substring(index);
    }

}

推荐阅读