繁体   English   中英

每隔4个字符拆分一个字符串?

[英]Split a string at every 4-th character?

我有一个字符串,如果可能的话我必须分成相等长度的子串。 我发现这个解决方案只有在字符串长度为4的倍数时才有效。

String   myString = "abcdefghijklm";
String[] split = myString.split("(?<=\\G....)");

这将产生:

[abcd, efgh, ijkl, m]

我需要的是从“字符串的末尾”拆分。 我想要的输出应该是这样的:

[a, bcde, fghi, jklm]

我如何实现这一目标?

这应该这样做:

String[] split = myString.split("(?=(....)+$)");
// or
String[] split = myString.split("(?=(.{4})+$)");

它的作用是:仅当空字符串在其前面有4个字符的倍数时才分割空字符串,直到达到输入结束。

当然,这有一个糟糕的运行时间(O(n ^ 2))。 您可以通过简单地自行分割来获得线性运行时算法。

如@anubhava所述:

(?!^)(?=(?:.{4})+$)如果字符串长度是4的倍数,则避免空结果

正则表达式真的没必要。 我也认为这不是递归的好问题。 以下是O(n)解决方案。

public static String[] splitIt(String input, int splitLength){

    int inputLength = input.length();
    ArrayList<String> arrayList = new ArrayList<>();

    int i = inputLength;
    while(i > 0){
        int beginIndex = i - splitLength > 0 ? i - splitLength : 0;
        arrayList.add(0, input.substring(beginIndex, i));
        i -= splitLength;
    }


    return arrayList.toArray(new String[0]);
}

无需使用正则表达式。 相反,您可以递归地构建头字符串列表并返回尾部。

import java.util.*;

public class StringChunker {
    public static void main(String[] args) {
        String str = "abcdefghijklm";

        System.out.println(Arrays.toString(chunk(str, 4)));        // [abcd, efgh, ijkl, m]
        System.out.println(Arrays.toString(chunk(str, 4, true)));  // [a, bcde, fghi, jklm]
    }

    public static String[] chunk(String str, int size) throws IllegalArgumentException {
        return chunk(str, size, false);
    }

    public static String[] chunk(String str, int size, boolean reverse) throws IllegalArgumentException {
        return chunk(str, size, reverse, new ArrayList<String>());
    }

    private static String[] chunk(String str, int size, boolean reverse, List<String> chunks) throws IllegalArgumentException {
        if (size < 1) {
            throw new IllegalArgumentException("size must be greater than 0");
        }
        if (str.length() < size) {
            if (reverse) {
                chunks.add(0, str); // Reverse adds to the front of the list
            } else {
                chunks.add(str); // Add to the end of the list
            }
            return chunks.toArray(new String[chunks.size()]); // Convert to an array
        } else {
            String head, tail;
            if (reverse) {
                head = str.substring(str.length() - size, str.length());
                tail = str.substring(0, str.length() - size);
                chunks.add(0, head);
            } else {
                head = str.substring(0, size);
                tail = str.substring(size);
                chunks.add(head);
            }
            return chunk(tail, size, reverse, chunks);
        }
    }
}

暂无
暂无

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

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