开发者

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:

  • How to find nth occurrence of character in a string?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜