简体   繁体   中英

Split a string in Java, based on delimiter, only once, if delimiter appears after given index

I was looking for a single step process to split a string, only once , based on a delimiter, only if the delimiter appears after certain index. For eg.

Input: String--> my-city-hasa-dash, Delimiter--> "-", index --> "3"

Though the first delimiter appears at 3rd position it is not > index supplied. so the regex should look for next occurrence of delimeter > index and split only once .

Output[]: {"mycity", "hasadash"}

Input: String--> m-ycityhasadash, Delimiter--> "-", index --> "3" Index of delimeter is less than the index supplied. So no split needed. Output[]: {"mycityhasadash"}

If you are using Java 8 you can use :

String[] output = Arrays.asList(
        str.replaceAll("^(.{0,2})-", "$1").split("-", 2))
        .stream()
        .map(x -> x.replace("-", ""))
        .toArray(String[]::new);

Outputs

my-city-hasa-dash - [mycity, hasadash]
m-ycityhasadash   - [mycityhasadash]

Details

  • str.replaceAll("^(.{0,2})-", "$1") will replace all the - before the first three characters
  • .split("-", 2) split your string two times
  • .map(x -> x.replace("-", "")) replace all the the - in the result outputs
  • .toArray(String[]::new) collect the result to an array

take a look at :

You can use a combination of String::substring and String::indexOf to get it:

String str = "my-city-hasa-dash";
String delimiter = "-";
int fromIndex = 3;
int delimiterIndex = str.indexOf(delimiter, fromIndex);
String[] output = delimiterIndex < 0 ? new String[]{str} :
        new String[]{
                str.substring(0, delimiterIndex).replace(delimiter, ""),
                str.substring(delimiterIndex).replace(delimiter, "")
        };

Output:

[mycity, hasadash]

import java.util.Arrays;
import java.util.stream.Collectors;

public class Test {

  public static void main(String ... args) {
    String input = "my-city-hasa-dash";

    String[] tokens = splitAfterIndex(input, "-", 2);

    System.out.println(Arrays.toString(tokens));

  }

  public static String[] splitAfterIndex(String str, String delimeter, int index) {
    String[] tokens = str.split(delimeter);

    String first = Arrays.stream(tokens).limit(index).collect(Collectors.joining());
    String second = Arrays.stream(tokens).skip(index).collect(Collectors.joining());

    return new String[] {second.isEmpty() ? first : first , second} ;

  }



}

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