【问题标题】:Android, String.split (String regex) doesn't split all the stringAndroid,String.split(字符串正则表达式)不会拆分所有字符串
【发布时间】:2017-08-09 14:49:43
【问题描述】:

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

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

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

【问题讨论】:

标签: java android regex split


【解决方案1】:

这里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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 2011-06-18
    相关资源
    最近更新 更多