fork download
  1. import java.util.*;
  2. class Main {
  3. static final char DELIM = ';';
  4. static final char ESCAPE = ':';
  5. public static void main(String[] args) {
  6. String a = "abc;def";
  7. String b = "ja:3fr";
  8. String c = ";";
  9. String d = "";
  10. String e = ":";
  11. String f = "83;:;:;;;;";
  12. String g = ":;";
  13.  
  14. String concat = concat(a,b,c,d,e,f,g);
  15.  
  16. String[] tokens = split(concat);
  17.  
  18. int pos = 0;
  19. System.out.println(test(a,tokens[pos++]));
  20. System.out.println(test(b,tokens[pos++]));
  21. System.out.println(test(c,tokens[pos++]));
  22. System.out.println(test(d,tokens[pos++]));
  23. System.out.println(test(e,tokens[pos++]));
  24. System.out.println(test(f,tokens[pos++]));
  25. System.out.println(test(g,tokens[pos++]));
  26. }
  27.  
  28. static String concat(String... ss) {
  29. StringBuilder sb = new StringBuilder();
  30. final String e = String.valueOf(ESCAPE);
  31. final String ee = e + ESCAPE;
  32. final String d = String.valueOf(DELIM);
  33. final String ed = e + d;
  34. for(String s : ss) {
  35. String r = s.replace(e, ee).replace(d, ed);
  36. System.out.println(s + " becomes " + r);
  37. sb.append(r).append(d);
  38. }
  39.  
  40. String fp = sb.toString().substring(0,sb.length() - 1);
  41. System.out.println("Final product:");
  42. System.out.println(fp);
  43. return fp; // trim off the last delim
  44. }
  45.  
  46. static String[] split(String concat) {
  47. List<String> tokens = new ArrayList<String>();
  48. StringBuilder sb = new StringBuilder();
  49. boolean escaped = false;
  50. for(int i = 0; i < concat.length(); i++) {
  51. char c = concat.charAt(i);
  52. if(c == ESCAPE && !escaped) {
  53. escaped = true;
  54. continue;
  55. }
  56. if(c == DELIM && !escaped) {
  57. tokens.add(sb.toString());
  58. sb = new StringBuilder();
  59. continue;
  60. }
  61. sb.append(c);
  62. escaped = false;
  63. }
  64. tokens.add(sb.toString());
  65. return tokens.toArray(new String[0]);
  66. }
  67.  
  68. static String test(String exp, String act) {
  69. return "Expected '" + exp + "', Actual '" + act + "', Matches " + exp.equals(act);
  70. }
  71. }
Success #stdin #stdout 0.03s 245632KB
stdin
Standard input is empty
stdout
abc;def becomes abc:;def
ja:3fr becomes ja::3fr
; becomes :;
 becomes 
: becomes ::
83;:;:;;;; becomes 83:;:::;:::;:;:;:;
:; becomes :::;
Final product:
abc:;def;ja::3fr;:;;;::;83:;:::;:::;:;:;:;;:::;
Expected 'abc;def', Actual 'abc;def', Matches true
Expected 'ja:3fr', Actual 'ja:3fr', Matches true
Expected ';', Actual ';', Matches true
Expected '', Actual '', Matches true
Expected ':', Actual ':', Matches true
Expected '83;:;:;;;;', Actual '83;:;:;;;;', Matches true
Expected ':;', Actual ':;', Matches true