简体   繁体   中英

Java split string on third comma

I have a string that I need to be split into 2. I want to do this by splitting at exactly the third comma.

How do I do this?

Edit

A sample string is :

from:09/26/2011,type:all,to:09/26/2011,field1:emp_id,option1:=,text:1234

The string will keep the same format - I want everything before field in a string.

If you're simply interested in splitting the string at the index of the third comma, I'd probably do something like this:

String s = "from:09/26/2011,type:all,to:09/26/2011,field1:emp_id,option1:=,text:1234";

int i = s.indexOf(',', 1 + s.indexOf(',', 1 + s.indexOf(',')));

String firstPart = s.substring(0, i);
String secondPart = s.substring(i+1);

System.out.println(firstPart);
System.out.println(secondPart);

Output:

from:09/26/2011,type:all,to:09/26/2011
field1:emp_id,option1:=,text:1234

Related question:

a naive implementation

public static String[] split(String s)
{
    int index = 0;
    for(int i = 0; i < 3; i++)
        index = s.indexOf(",", index+1);

    return new String[] {
            s.substring(0, index),
            s.substring(index+1)
    };
}

This does no bounds checking and will throw all sorts of lovely exceptions if not given input as expected. Given "ABCD,EFG,HIJK,LMNOP,QRSTU" returns ["ABCD,EFG,HIJK","LMNOP,QRSTU"]

You can use this regex:

^([^,]*,[^,]*,[^,]*),(.*)$

The result is then in the two captures (1 and 2), not including the third comma.

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