How to split the string before the 2nd occurrence of a character in Java

10,526

Solution 1

I assume you need first two string, then do the following:

    String[] res = Arrays.copyOfRange(string.split(" "), 0, 2);

Solution 2

You can do this:-

String[] s=string.split("");
s[2]=null;
s[3]=null;

Now you only have {1234},{2345}

OR the better way , part the String itself then apply split()

String s=string.substring(string.indexOf("1"),string.indexOf("5")+1);// +1 for including the 5
s.split(" ");

Solution 3

You have any options, one is to do the split and copy the first 2 results.

The next code has the next output:

First two:
1234

2345

    public static void main(String[] args) {
    String input="1234 2345 3456 4567";

    String[] parts= input.split(" ");
    String[] firstTwoEntries = Arrays.copyOf(parts, 2);

    System.out.println("First two: ");
    System.out.println("----------");
    for(String entry:firstTwoEntries){
        System.out.println(entry);
    }
    System.out.println("----------");
}

Another is to replace the original string with a regexp and after do the split:

Result of the next code(we replace the space with ":":

Filtered: 1234:2345

First two:

1234

2345

    public static void main(String[] args) {
    String input="1234 2345 3456 4567";

    //we find first 2 and separate with :
    String filteredInput= input.replaceFirst("^([^\\s]*)\\s([^\\s]*)\\s.*$", "$1:$2");
    System.out.println("Filtered: "+filteredInput);

    String[] parts= filteredInput.split(":");
    System.out.println("First two: ");
    System.out.println("--------");
    for(String part:parts){
        System.out.println(part);
    }
    System.out.println("--------");

}
Share:
10,526
HackCode
Author by

HackCode

Updated on June 15, 2022

Comments

  • HackCode
    HackCode almost 2 years

    I have:

    1234 2345 3456 4567
    

    When I try String.split(" ",2), I get:

    {1234} , {2345 3456 4567}
    

    But I need:

    {1234},{2345}
    

    I want only the first two elements. How do I implement this in Java?
    Thanks in advance.

    EDIT:This is just one line of a huge dataset.