跳到主要内容

编写一个Java截取字符串的函数 ?

参考答案:

在Java中,你可以使用substring函数来截取字符串。以下是一个简单的示例,这个函数接收一个字符串和两个整数参数,分别代表开始和结束的索引,然后返回截取后的子字符串。

public class Main {
    public static void main(String[] args) {
        String str = "Hello, World!";
        System.out.println(substringBetweenIndexes(str, 0, 5));  // 输出: "Hello"
    }

    public static String substringBetweenIndexes(String str, int startIndex, int endIndex) {
        if (str == null) {
            return null;
        }

        if (startIndex < 0 || endIndex > str.length() || startIndex > endIndex) {
            throw new IndexOutOfBoundsException("Invalid index range: startIndex = " + startIndex + ", endIndex = " + endIndex + ", string length = " + str.length());
        }

        return str.substring(startIndex, endIndex);
    }
}

这个函数首先检查传入的字符串是否为null,然后检查提供的索引是否在有效范围内。如果索引无效,它将抛出一个IndexOutOfBoundsException。如果索引有效,它将使用substring方法从字符串中提取子字符串,并返回该子字符串。

注意,Java的substring方法的第二个参数是子字符串的结束索引(不包括在内)。因此,如果你想要获取从索引5到字符串末尾的所有字符,你应该使用str.substring(5),而不是str.substring(5, str.length())