2

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.

aioobe
  • 413,195
  • 112
  • 811
  • 826
pm13
  • 735
  • 7
  • 23
  • 36

3 Answers3

4

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:

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • quick question - would this work if I wanted to get every third comma? – pm13 Sep 27 '11 at 10:22
  • Naah, then you probably want a loop of some kind. Have a look at the related question I posted. Alternatively, why don't you split on `","` and join the parts you want grouped together. – aioobe Sep 27 '11 at 10:24
2

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"]

mcfinnigan
  • 11,442
  • 35
  • 28
1

You can use this regex:

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

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

Lucero
  • 59,176
  • 9
  • 122
  • 152
  • That just returned my full string. I have edited the above with a sample string – pm13 Sep 27 '11 at 09:57
  • @pm13, yes it does match the full string, but the captures (as I wrote) contain the two distinct parts. – Lucero Sep 27 '11 at 11:35