fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. String s = "ex1 , [ex2 , ex3 ] , [ hh3 , rt5 , w3 [ bn7 ] ] , ex 4 , ex 4, [ex , ex ]";
  13. List<String> res = splitWithCommaOutsideBrackets(s);
  14. for (String t: res) {
  15. System.out.println(t);
  16. }
  17. }
  18.  
  19. public static List<String> splitWithCommaOutsideBrackets(String input) {
  20. int BracketCount = 0;
  21. int start = 0;
  22. List<String> result = new ArrayList<>();
  23. for(int i=0; i<input.length(); i++) {
  24. switch(input.charAt(i)) {
  25. case ',':
  26. if(BracketCount == 0) {
  27. result.add(input.substring(start, i).trim());
  28. start = i+1;
  29. }
  30. break;
  31. case '[':
  32. BracketCount++;
  33. break;
  34. case ']':
  35. BracketCount--;
  36. if(BracketCount < 0)
  37. return result; // The BracketCount shows the [ and ] number is unbalanced
  38. break;
  39. }
  40. }
  41. if(BracketCount > 0)
  42. return result; // Missing closing ]
  43. result.add(input.substring(start).trim());
  44. return result;
  45. }
  46. }
Success #stdin #stdout 0.09s 320576KB
stdin
Standard input is empty
stdout
ex1
[ex2 , ex3 ]
[ hh3 , rt5 , w3 [ bn7 ] ]
ex 4
ex 4
[ex , ex ]