Split a String at every 3rd comma in Java

后端 未结 4 1983
礼貌的吻别
礼貌的吻别 2020-11-30 14:26

I have a string that looks like this:

0,0,1,2,4,5,3,4,6

What I want returned is a String[]

4条回答
  •  暖寄归人
    2020-11-30 14:30

    Nice one for the coding dojo! Here's my good old-fashioned C-style answer:

    If we call the bits between commas 'parts', and the results that get split off 'substrings' then:

    n is the amount of parts found so far, i is the start of the next part, startIndex the start of the current substring

    Iterate over the parts, every third part: chop off a substring.

    Add the leftover part at the end to the result when you run out of commas.

    List result = new ArrayList();
    int startIndex = 0;
    int n = 0;
    for (int i = x.indexOf(',') + 1; i > 0; i = x.indexOf(',', i) + 1, n++) {
        if (n % 3 == 2) {
            result.add(x.substring(startIndex, i - 1));
            startIndex = i;
        }
    }
    result.add(x.substring(startIndex));
    

提交回复
热议问题