gpt4 book ai didi

java - Android, String.split (String regex) 不拆分所有字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:13:19 25 4
gpt4 key购买 nike

我对 String.split(String regex) 有疑问。我想将我的字符串分成 4 个字符的部分。

String stringa = "1111110000000000"
String [] result = stringa.split("(?<=\\G....)")

当我打印结果时,我期望 1111,1100,0000,0000 但结果是 1111,110000000000。我该如何解决?谢谢。

最佳答案

在这里a solution without regex -

您从字符串的末尾开始,提取 4 个或更少的字符并将它们添加到列表中:

public static void main (String[] args) {
String stringa = "11111110000000000";
List<String> result = new ArrayList<>();

for (int endIndex = stringa.length(); endIndex >= 0; endIndex -= 4) {
int beginIndex = Math.max(0, endIndex - 4);
String str = stringa.substring(beginIndex, endIndex);
result.add(0, str);
}

System.out.println(result);
}

输出结果:

[1, 1111, 1100, 0000, 0000]

关于java - Android, String.split (String regex) 不拆分所有字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42867799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com