簡體   English   中英

如何基於Java中子字符串的長度將字符串轉換為子字符串數組?

[英]How to convert string to array of substrings based on the length of substring in java?

我想根據子字符串的長度將字符串轉換為子字符串數組。 有沒有不使用循環的解決方案? 例如:

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

更新:

此處提供更多解決方案: 在第n個字符處分割字符串

看一下Bart Kiers的例子

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

周期數“。” 指示每個子字符串多少個字符。


編輯

正如Mick Mnemonic所指出的,您還可以使用Kevin Bourrillion的示例

Java沒有提供功能非常齊全的拆分工具,因此Guava庫提供了

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

查看Javadoc for Splitter ; 它非常強大。

如果您不想使用正則表達式, 並且不想依賴第三方庫,則可以改用此方法,在2.80 GHz CPU (不到一毫秒)中,此方法花費89920100113納秒:

   /**
     * 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()]);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM