簡體   English   中英

將字符串拆分到第n個定界符

[英]Splitting a string to the nth delimiter

我正在嘗試拆分字符串,保留定界符並基於第N個定界符保存到新字符串。 例如。

String s = "HELLO-WORLD-GREAT-DAY"

我想存儲HELLO-WORLD-GREAT並砍掉-DAY

我可以使用split[x]捕獲單個元素,但似乎無法找出將其聲明為新string以供以后使用的最佳方法。

有什么主意嗎?

我嘗試過使用split last和first等。

我需要能夠捕獲輸入字符串的前三個元素

拆分並合並:

public String removeLast(String input) {
    //Split your input
    String[] parts = input.split("-");

    //Combine to a new string, leaving out the last one
    String output = parts[0];
    for (int i = 1; i < parts.length - 1; i++) {
        output += "-" + parts[i];
    }
    return output;
}

請嘗試以下操作:

public String removeLast(String target, String delimiter) {
    int pos = target.lastIndexOf(delimiter);
    return pos == -1 ? target : target.substring(0, pos);
}

您將這樣調用方法:

String result = removeLast("HELLO-WORLD-GREAT-DAY", "-");

我可以想到兩種簡單的方法:

String hw = "HELLO-WORLD-GREAT-DAY"

def result = hw - hw.substring(hw.lastIndexOf('-'))

String.joinsplit的結果:

def result = String.join('-', hw.split('-')[0..-2])

有了groovy,您可以做到

​"HELLO-WORLD-GREAT-DAY".split('-')[0..-2].join('-')​​​​

暫無
暫無

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

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