我有一个字符串需要分割成等长的子字符串。我找到了这个解决方案,但只适用于字符串长度是4的倍数的情况。
String myString = "abcdefghijklm";
String[] split = myString.split("(?<=\\G....)");
这将产生以下结果:
[abcd, efgh, ijkl, m]
我需要从字符串的末尾拆分。我期望得到的输出应该像这样:
[a, bcde, fghi, jklm]
我该如何实现这个目标?
我有一个字符串需要分割成等长的子字符串。我找到了这个解决方案,但只适用于字符串长度是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})+$)");
[a, bcde, fghi, jklm]
。 - Ole V.V.(?!^)(?=(?:.{4})+$)
如果字符串长度是4的倍数,则避免返回空结果。 - anubhavapublic 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);
}
}
}