2

I would like to split a string at every 4th occurrence of a comma ,.

How to do this? Below is an example:

String str = "1,,,,,2,3,,1,,3,,";

Expected output:
array[0]: 1,,,,
array[1]: ,2,3,,
array[2]: 1,,3,,

I tried using Google Guava like this:

Iterable<String> splitdata = Splitter.fixedLength(4).split(str);
output: [1,,,, ,,2,, 3,,1, ,,3,, ,]

I also tried this:

String [] splitdata = str.split("(?<=\\G.{" + 4 + "})");
output: [1,,,, ,,2,, 3,,1, ,,3,, ,]

Yet this is is not the output I want. I just want to split the string at every 4th occurrence of a comma.

Thanks.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Miss A
  • 47
  • 1
  • 7

5 Answers5

2

Take two int variable. One is to count the no of ','. If ',' occurs then the count will move. And if the count is go to 4 then reset it to 0. The other int value will indicate that from where the string will be cut off. it will start from 0 and after the first string will be detected the the end point (char position in string) will be the first point of the next. Use the this start point and current end point (i+1 because after the occurrence happen the i value will be incremented). Finally add the string in the array list. This is a sample code. Hope this will help you. Sorry for my bad English.

String str = "1,,,,,2,3,,1,,3,,";
int k = 0;
int startPoint = 0;
ArrayList<String> arrayList = new ArrayList<>();
for (int i = 0; i < str.length(); i++)
{
  if (str.charAt(i) == ',')
  {
      k++;
      if (k == 4)
      {
          String ab = str.substring(startPoint, i+1);
          System.out.println(ab);
          arrayList.add(ab);
          startPoint = i+1;
          k = 0;
      }
  }
}
Saqib Rezwan
  • 1,382
  • 14
  • 20
  • This does not add leftover items to the list. If the length of the string is 9, It won't add the 9th element to list. – skr Jul 04 '22 at 13:52
1

Here's a more flexible function, using an idea from this answer:

static List<String> splitAtNthOccurrence(String input, int n, String delimiter) {
    List<String> pieces = new ArrayList<>();
    // *? is the reluctant quantifier
    String regex = Strings.repeat(".*?" + delimiter, n);
    Matcher matcher = Pattern.compile(regex).matcher(input);

    int lastEndOfMatch = -1;
    while (matcher.find()) {
        pieces.add(matcher.group());
        lastEndOfMatch = matcher.end();
    }
    if (lastEndOfMatch != -1) {
        pieces.add(input.substring(lastEndOfMatch));
    }
    return pieces;
}

This is how you call it using your example:

String input = "1,,,,,2,3,,1,,3,,";
List<String> pieces = splitAtNthOccurrence(input, 4, ",");
pieces.forEach(System.out::println);
// Output:
// 1,,,,
// ,2,3,,
// 1,,3,,

I use Strings.repeat from Guava.

Community
  • 1
  • 1
Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
0

try this also, if you want result in array

    String str = "1,,,,,2,3,,1,,3,,";
    System.out.println(str);
    char c[] = str.toCharArray();
    int ptnCnt = 0;
    for (char d : c) {
        if(d==',')
            ptnCnt++;
    }
    String result[] = new String[ptnCnt/4];
    int i=-1;
    int beginIndex  = 0;
    int cnt=0,loopcount=0;
    for (char ele : c) {
        loopcount++;
        if(ele==',')
            cnt++;
        if(cnt==4){
            cnt=0;
            result[++i]=str.substring(beginIndex,loopcount);
            beginIndex=loopcount;
        }
    }
    for (String string : result) {
        System.out.println(string);
    }
Babu Pasungily
  • 315
  • 3
  • 13
0

This work pefectly and tested in Java 8

public String[] split(String input,int at){
    String[] out = new String[2];
    String p = String.format("((?:[^/]*/){%s}[^/]*)/(.*)",at);
    Pattern pat = Pattern.compile(p);
    Matcher matcher = pat.matcher(input);
       if (matcher.matches()) {
          out[0] = matcher.group(1);// left
          out[1] = matcher.group(2);// right
       }
    return out;
} 

//Ex: D:/folder1/folder2/folder3/file1.txt
//if at = 2, group(1) = D:/folder1/folder2  and group(2) = folder3/file1.txt
0

The accepted solution above by Saqib Rezwan does not add the leftover string to the list, if it divides the string after every 4th comma and the length of the string is 9 then it will leave the 9th character, and return the wrong list.

A complete solution would be :

  private static ArrayList<String> splitStringAtNthOccurrence(String str, int n) {
        int k = 0;
        int startPoint = 0;
        ArrayList<String> list = new ArrayList();
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ',') {
                k++;
                if (k == n) {
                    String ab = str.substring(startPoint, i + 1);
                    list.add(ab);
                    startPoint = i + 1;
                    k = 0;
                }
            } 
        // if there is no comma left and there are still some character in the string
        // add them to list
            else if (!str.substring(i).contains(",")) {
                list.add(str.substring(startPoint));
                break;
            }
        }
        return list;
    }
}
skr
  • 1,700
  • 1
  • 15
  • 39