简体   繁体   中英

Splitting a string to the nth delimiter

I am trying to split a string, keep the delimiters and save to a new string based on the Nth delimiter. For example.

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

I would like to store HELLO-WORLD-GREAT and chop off the -DAY .

I can capture the individual elements using split[x] but I cant seem to figure out the best way to assert this to a new string to be used later on.

Any idea's folks?

I have tried to use split last and first etc.

I need to be able to capture first three elements of the input string

Split and combine:

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;
}

Try the following:

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

You would call the method like this:

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

Two easy ways I can think of:

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

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

And String.join with split 's result:

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

有了groovy,您可以做到

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM