【问题标题】:Cannot convert Array to List of String correctly无法正确将数组转换为字符串列表
【发布时间】:2014-11-03 09:24:21
【问题描述】:

有固定长度的字符串,每条记录必须吐出 15 个字符。结果应该放在List,但是看起来整个字符串总是放在List中的0位置。

Arrays.asList(a1.substring(1,324).split("[a-zA-Z]{20}"))

这是为什么呢?

更新:

List<String> l =  Arrays.asList("1111111111     1119999999                                                                                              ".split("[0-9]{15}"));

【问题讨论】:

  • 请给我们样本输入/输出。没有人愿意猜测。
  • 你认为split("[a-zA-Z]{20}") 会做什么?
  • 应该是split("\.{20}")
  • 我不是说你应该改变它,我是问你认为它有什么作用(你认为你应该得到什么结果)?还有它的文档的哪一部分让您认为应该预期这样的结果?
  • @Pshemo,如果在集合 [a-zA-Z] 中找到连续的 20 个字符,它会拆分字符串。空格不匹配。对吗?

标签: java string


【解决方案1】:

拆分正则表达式应该是:

String[] arr = str.split("(?<=\\G.{20})");

以上每 20 个字符拆分 str

例如下面的代码将 str 拆分为每 15 个字符:

 String str ="hkdhadhkshdkhskhdkashdkasgi2oyeihsadkahdkashdlkhas";
             List<String> list = Arrays.asList(str.split("(?<=\\G.{15})"));
            System.out.println(list);

打印:

[hkdhadhkshdkhsk, hdkashdkasgi2oy, eihsadkahdkashd, lkhas]

【讨论】:

  • 简洁明了!这部分我不是很懂?&lt;=\\G
  • +1 不错的拆分正则表达式。没有多少人知道这需要\G,甚至知道\G 做了什么。
  • @RCola \G 表示前一个匹配的结束,或者如果没有前一个匹配(如果我们正在寻找第一个匹配)它表示字符串的开始(相当于^ )。
  • @pshemo 这让我想起了your stellar answer,这是我了解\G 的方式。它仍然是我在网站上最喜欢的答案 - 它改变了我的生活 :)
  • 也就是说,匹配一个空字符串,从上一个匹配的末尾开始,在 15 个字符之后。
【解决方案2】:

从你的问题:

有固定长度的字符串,每条记录必须吐出 15 个字符。结果应该放在List

String.split() 并不适合这样的事情。它被设计为在分隔符上拆分,“每 15 个字符”不是。

您正在寻找String.substring() 中的功能,它返回String,即[beginIndex, endIndex) 之间的序列。

用这个方法:

public static List<String> splitByIndex(String toSplit, int index) { 
    List<String> result = new ArrayList<String>(); 
    for (int i = 0; i < toSplit.length(); i += index) { 
        if (i + index < toSplit.length()) {
            result.add(toSplit.substring(i, i + index));
        } else {
            result.add(toSplit.substring(i, toSplit.length() - 1));
        }
    }
    return result; 
}

您可以将String 按给定字符数拆分为List&lt;String&gt;。本示例代码:

String a1 = "I'm the fixed length string that needs to be split by 15 characters.";
List<String> list = splitByIndex(a1, 15);
System.out.println(list);

将输出:

[I'm the fixed l, ength string th, at needs to be , split by 15 cha, racters]

【讨论】:

    猜你喜欢
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    相关资源
    最近更新 更多