欢迎访问宙启技术站
智能推送

Java函数:如何把一个字符串按照指定长度分割?

发布时间:2023-08-10 20:58:17

要将一个字符串按照指定长度分割,可以使用如下的Java函数:

public static List<String> splitString(String input, int length) {
    List<String> result = new ArrayList<>();
    int startIndex = 0;
    while (startIndex < input.length()) {
        int endIndex = Math.min(startIndex + length, input.length());
        String substring = input.substring(startIndex, endIndex);
        result.add(substring);
        startIndex += length;
    }
    return result;
}

这个函数接受两个参数: 个参数是要分割的字符串,第二个参数是指定的长度。函数会返回一个包含分割后的子字符串的列表。如果字符串的长度无法整除指定的长度,最后一个子字符串的长度可能会小于指定的长度。

以下是一个使用示例:

String input = "1234567890abcdefghijklmnopqrstuvwxuz";
int length = 10;
List<String> result = splitString(input, length);
for (String substring : result) {
    System.out.println(substring);
}

输出为:

1234567890
abcdefghij
klmnopqrst
uvwxuz

在这个示例中,字符串"1234567890abcdefghijklmnopqrstuvwxuz"被按照长度为10进行了分割。每个子字符串的长度都是10,除了最后一个子字符串的长度为6。