LodgerLabit
LodgerLabit

Reputation: 11

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

Upvotes: 0

Views: 646

Answers (4)

ernest_k
ernest_k

Reputation: 45309

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])

Upvotes: 1

tim_yates
tim_yates

Reputation: 171084

With groovy you can do

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

Upvotes: 0

kske
kske

Reputation: 138

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", "-");

Upvotes: 1

MWB
MWB

Reputation: 1879

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

Upvotes: 1

Related Questions