Miss A Miss A - 11 months ago 58
Java Question

How to split array every nth occurence of character in java

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.


Answer Source

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) == ',')
      if (k == 4)
          String ab = str.substring(startPoint, i+1);
          startPoint = i+1;
          k = 0;