代码之家  ›  专栏  ›  技术社区  ›  Jonik

在Java中将字符串分割成n个长度的块[重复]

  •  6
  • Jonik  · 技术社区  · 14 年前

    可能重复:
    Split string to equal length substrings in Java

    /**
     * Splits string <tt>s</tt> into chunks of size <tt>chunkSize</tt>
     *
     * @param s the string to split; must not be null
     * @param chunkSize number of chars in each chuck; must be greater than 0
     * @return The original string in chunks
     */
    public static List<String> splitInChunks(String s, int chunkSize) {
        Preconditions.checkArgument(chunkSize > 0);
        List<String> result = Lists.newArrayList();
        int length = s.length();
        for (int i = 0; i < length; i += chunkSize) {
            result.add(s.substring(i, Math.min(length, i + chunkSize)));
        }
        return result;
    }
    

    (一) 在任何一个普通的Java库中都有等价的方法吗

    (显然,我不会仅仅为了这个而向某个庞大的框架添加依赖项,但可以随意提及任何公共库;也许我已经使用了它。)

    2个) 如果没有,有没有更简单、更干净的方法在Java中实现这一点? 还是一种更具表现力的方式?(如果您建议使用基于regex的解决方案,请考虑非regex专家可读性方面的清洁度。。。:-)

    :这符合问题的副本” Split string to equal length substrings in Java “因为 this Guava solution 这完全回答了我的问题!

    2 回复  |  直到 8 年前
        1
  •  14
  •   Community CDub    8 年前

    你可以用番石榴做这个 Splitter :

     Splitter.fixedLength(chunkSize).split(s)
    

    …它返回一个 Iterable<String>

    中的更多示例 this answer .

        2
  •  1
  •   Community CDub    8 年前

    基本上是 Split Java String in chunks of 1024 bytes 把它转换成流并一次读取N个字节的想法似乎能满足您的需要?

    Here is a way of doing it with regex