fork 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. System.out.println(split(" jack for { 123 for{}} rose for {}"));
  13. System.out.println(split(" jack for { 123 for{} foo} rose for {}"));
  14. System.out.println(split(" jack for { 123 for{}foo}fee rose for fum{}"));
  15. }
  16.  
  17. private static List<String> split(String input) {
  18. Scanner sc = new Scanner(input);
  19. sc.useDelimiter("");
  20. List<String> resultingParts = new ArrayList<>();
  21. int currentNestingDepth=0;
  22. StringBuilder currentPart= new StringBuilder();
  23. while (sc.hasNext()) {
  24. char c = sc.next().charAt(0);
  25. if (c == '{') { currentNestingDepth++; }
  26. else if (c == '}') {
  27. currentNestingDepth--; //!\\ might fail with unbalanced parens, test > 0 if needed
  28. if (currentNestingDepth == 0) {
  29. currentPart.append(c);
  30. resultingParts.add(currentPart.toString());
  31. currentPart = new StringBuilder();
  32. continue; // to avoid adding the current character yet again
  33. }
  34. }
  35. currentPart.append(c);
  36. }
  37. if (currentPart.length() > 0) { resultingParts.add(currentPart.toString()); }
  38. return resultingParts;
  39. }
  40. }
Success #stdin #stdout 0.11s 35288KB
stdin
Standard input is empty
stdout
[  jack   for { 123 for{}},  rose for {}]
[  jack   for { 123 for{} foo},  rose for {}]
[  jack   for { 123 for{}foo}, fee rose for fum{}]