如何根据java中子字符串的长度将字符串转换为子字符串数组?

时间:2018-01-31 19:27:21

标签: java regex string

我想根据子字符串的长度将字符串转换为子字符串数组。有没有使用循环的解决方案? 例如:

"this is a test" -> ["thi","s i","s a"," te","st"]

更新

此处有更多解决方案:Splitting a string at every n-th character

1 个答案:

答案 0 :(得分:3)

查看Bart Kiers' example

  

System.out.println(java.util.Arrays.toString("this is a test".split("(?<=\\G...)")));

期数'。'表示每个子字符串的字符数。

修改

正如Mick Mnemonic所指出的,您还可以使用Kevin Bourrillion's example

  

Java没有提供功能非常全面的拆分工具,所以   Guava libraries做:

     

Iterable<String> pieces = Splitter.fixedLength(3).split(string);

     

检查   出Javadoc for Splitter;它非常强大。

如果您不想使用正则表达式,不希望依赖第三方库,则可以使用此方法,  在 2.80 GHz CPU (小于1毫秒)内 89920 100113 纳秒:

   /**
     * Divides the given string into substrings each consisting of the provided
     * length(s).
     * 
     * @param string
     *            the string to split.
     * @param defaultLength
     *            the default length used for any extra substrings. If set to
     *            <code>0</code>, the last substring will start at the sum of
     *            <code>lengths</code> and end at the end of <code>string</code>.
     * @param lengths
     *            the lengths of each substring in order. If any substring is not
     *            provided a length, it will use <code>defaultLength</code>.
     * @return the array of strings computed by splitting this string into the given
     *         substring lengths.
     */
    public static String[] divideString(String string, int defaultLength, int... lengths) {
        java.util.ArrayList<String> parts = new java.util.ArrayList<String>();

        if (lengths.length == 0) {
            parts.add(string.substring(0, defaultLength));
            string = string.substring(defaultLength);
            while (string.length() > 0) {
                if (string.length() < defaultLength) {
                    parts.add(string);
                    break;
                }
                parts.add(string.substring(0, defaultLength));
                string = string.substring(defaultLength);
            }
        } else {
            for (int i = 0, temp; i < lengths.length; i++) {
                temp = lengths[i];
                if (string.length() < temp) {
                    parts.add(string);
                    break;
                }
                parts.add(string.substring(0, temp));
                string = string.substring(temp);
            }
            while (string.length() > 0) {
                if (string.length() < defaultLength || defaultLength <= 0) {
                    parts.add(string);
                    break;
                }
                parts.add(string.substring(0, defaultLength));
                string = string.substring(defaultLength);
            }
        }

        return parts.toArray(new String[parts.size()]);
    }