簡體   English   中英

在每個第n個位置拆分一個字符串

[英]Split a string, at every nth position

我使用這個正則表達式在每個第三個位置分割一個字符串:

String []thisCombo2 = thisCombo.split("(?<=\\G...)");

其中G之后的3個點表示要分割的每個第n個位置。 在這種情況下,3個點表示每3個位置。 一個例子:

Input: String st = "123124125134135145234235245"
Output: 123 124 125 134 135 145 234 235 245.

我的問題是,如何讓用戶控制必須拆分字符串的位置數? 換句話說,如何制作用戶控制的3個點,n個點?

為了大幅提升性能,另一種方法是在循環中使用substring()

public String[] splitStringEvery(String s, int interval) {
    int arrayLength = (int) Math.ceil(((s.length() / (double)interval)));
    String[] result = new String[arrayLength];

    int j = 0;
    int lastIndex = result.length - 1;
    for (int i = 0; i < lastIndex; i++) {
        result[i] = s.substring(j, j + interval);
        j += interval;
    } //Add the last bit
    result[lastIndex] = s.substring(j);

    return result;
}

例:

Input:  String st = "1231241251341351452342352456"
Output: 123 124 125 134 135 145 234 235 245 6.

它不像stevevls的解決方案那么短,但它的效率更高 (見下文),我認為將來更容易調整,當然這取決於你的情況。


性能測試(Java 7u45)

2,000個字符長字符串 - 間隔為3

split("(?<=\\\\G.{" + count + "})")性能(以毫秒為單位):

7, 7, 5, 5, 4, 3, 3, 2, 2, 2

splitStringEvery()substring() )性能(以毫秒為單位):

2, 0, 0, 0, 0, 1, 0, 1, 0, 0

2,000,000個字符長字符串 - 間隔為3

split()性能(以毫秒為單位):

207, 95, 376, 87, 97, 83, 83, 82, 81, 83

splitStringEvery()性能(以毫秒為單位):

44, 20, 13, 24, 13, 26, 12, 38, 12, 13

2,000,000個字符長字符串 - 間隔為30

split()性能(以毫秒為單位):

103, 61, 41, 55, 43, 44, 49, 47, 47, 45

splitStringEvery()性能(以毫秒為單位):

7, 7, 2, 5, 1, 3, 4, 4, 2, 1

結論:

splitStringEvery()方法要快得多 (即使在Java 7u6中發生更改之后),並且當間隔變得更高時它會升級

即用型測試代碼:

pastebin.com/QMPgLbG9

您可以使用大括號運算符指定角色必須出現的次數:

String []thisCombo2 = thisCombo.split("(?<=\\G.{" + count + "})");

大括號是一個方便的工具,因為您可以使用它來指定精確的計數或范圍。

使用Google Guava ,您可以使用Splitter.fixedLength()

返回將字符串分成給定長度的片段的拆分器

Splitter.fixedLength(2).split("abcde");
// returns an iterable containing ["ab", "cd", "e"].

如果要構建該正則表達式字符串,可以將拆分長度設置為參數。

public String getRegex(int splitLength)
{
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < splitLength; i++)
        builder.append(".");

    return "(?<=\\G" + builder.toString() +")";
}
private String[] StringSpliter(String OriginalString) {
    String newString = "";
    for (String s: OriginalString.split("(?<=\\G.{"nth position"})")) { 
        if(s.length()<3)
            newString += s +"/";
        else
            newString += StringSpliter(s) ;
    }
    return newString.split("/");
}

暫無
暫無

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

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