Home > Software design >  Split string in reverse
Split string in reverse

Time:04-09

I have a string sub1-sub2-sub3 which I want to split from right to left. Currently I am using split function like this which splits the string from left to right -

String str = "sub1-sub2-sub3";
System.out.println("Result :"   str.split("-", 2));

Elements in output :

sub1
sub2-sub3

Desired output :

sub1-sub2
sub3

Is there a way where I can split my string on - starting from right?

CodePudding user response:

You could do a regex split on -(?!.*-):

String str = "sub1-sub2-sub3";
String[] parts = str.split("-(?!.*-)");
System.out.println(Arrays.toString(parts));  // [sub1-sub2, sub3]

The regex pattern used here will only match the final dash.

CodePudding user response:

A generic solution as utility method that takes limit as input with java 8:

public List<String> splitReverse(String input, String regex, int limit) {
    return Arrays.stream(reverse(input).split(regex, limit))
            .map(this::reverse)
            .collect(Collectors.toList());
}

private String reverse(String i){
    return new StringBuilder(i).reverse().toString();
}

reverse() code taken from here

Input: sub1-sub2-sub3

Reverse input: 3bus-2bus-1bus

Split(rev,2): [3bus] , [2bus-1bus]

Reverse each: [sub3] , [sub1-sub2]

CodePudding user response:

A quick and dirty solution i cam up with would be

    String str = "sub1-sub2-sub3";
    str = StringUtils.reverse(str);

    String[] split = str.split("-", 2);
    split[0] = StringUtils.reverse(split[0]);
    split[1] = StringUtils.reverse(split[1]);

    System.out.println("Result :"   split[0]   " #### "   split[1]);

another way would be java how to split string from end

CodePudding user response:

The below solution worked for me fine :

str.substring(0, str.lastIndexOf("-"));
str.substring(str.lastIndexOf("-"));
  • Related