Java:如何用一些字符拆分字符串?

Mer*_*yth 28 java string split numbers character

我试图在网上搜索解决这个问题,但我没有找到任何东西.

我写了以下抽象代码来解释我在问什么:

String text = "how are you?";

String[] textArray= text.splitByNumber(4); //this method is what I'm asking
textArray[0]; //it contains "how "
textArray[1]; //it contains "are "
textArray[2]; //it contains "you?"
Run Code Online (Sandbox Code Playgroud)

splitByNumber方法每4个字符拆分字符串"text".我怎么能创建这个方法?

非常感谢

Gui*_*let 61

我认为他想要的是将一个字符串拆分为大小为4的子串.然后我会在循环中执行此操作:

List<String> strings = new ArrayList<String>();
int index = 0;
while (index < text.length()) {
    strings.add(text.substring(index, Math.min(index + 4,text.length())));
    index += 4;
}
Run Code Online (Sandbox Code Playgroud)


bru*_*nde 28

使用番石榴:

Iterable<String> result = Splitter.fixedLength(4).split("how are you?");
String[] parts = Iterables.toArray(result, String.class);
Run Code Online (Sandbox Code Playgroud)


Sam*_*isa 10

正则表达式怎么样?

public static String[] splitByNumber(String str, int size) {
    return (size<1 || str==null) ? null : str.split("(?<=\\G.{"+size+"})");
}
Run Code Online (Sandbox Code Playgroud)

请参阅Java中的将字符串拆分为相等长度的子字符串