简体   繁体   English

Java API将字符串拆分为不同长度的子字符串

[英]Java API to split a string into substrings of different length

I have a input string of known length. 我有一个已知长度的输入字符串。 I have to split this input string in 30 substrings of different lengths. 我必须将此输入字符串分成30个不同长度的子字符串。 For ex:- 例如:

Input string: "abcdefghijklmnopqrstuvwxyz"
Output string: "a","bcd","efgij","kl","mnopqrstu","v","wx","yz"

I wanted to know if there is some sort of API or way where I can provide the lengths, based on which I want to split the string, and get the output at one go instead of multiple steps. 我想知道是否有某种API或方法可以提供长度,根据该长度或长度我想分割字符串,并一次性获得输出而不是多个步骤。

Any help will be highly appreciated. 任何帮助将不胜感激。

One way which works out of the box is using RegEx . 开箱即用的一种方法是使用RegEx Here's an example that splits it into 4, 3, 5, 2 and the rest of the string (the first value of the mathed groups is the entire string, that's why I started from 1): 这是一个将其分为4、3、5、2和其余字符串的示例(数学组的第一个值是整个字符串,这就是为什么我从1开始):

String input = "abcdefghijklmnopqrstuvwxyz";
Matcher m = Pattern.compile("^(.{4})(.{3})(.{5})(.{2})(.*)").matcher(input);
if (m.matches()) {
    for (int i = 1; i <= m.groupCount(); i++) {
        System.out.println(m.group(i));
    }
}

however this is much slower than splitting the string using a simple for, using the dimensions given. 但是,这比使用给定尺寸的简单for分割字符串要慢得多。 You need to take into account speed and quality over ease of use. 您需要在易用性上考虑速度和质量。

More about regular expressions: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html 有关正则表达式的更多信息: https : //docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

No need for an API. 无需API。 It took just 1 minute to write a method to do that: 只需1分钟即可编写一个方法来做到这一点:

public static List<String> splitString(String inputString, int... lengths) {

    List<String> substrings = new ArrayList<String>();

    int start = 0;
    int end = 0;

    for(int length : lengths) {

        start = end;
        end = start + length;

        String substring  = inputString.substring(start, end);
        substrings.add(substring);
    }

    return substrings;
}

Calling splitString("abcdefghi", 3, 4, 2) will produce : [abc, defg, hi] 调用splitString(“ abcdefghi”,3,4,2)将产生:[abc,defg,hi]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM