title: Creating my on split method that includes delimiters
body: <p>I am trying to create my own split method that includes the delimiters in the output.  I have this code so far:</p>
  
  <pre><code>private static String[] split(String string, String regex) throws InterruptedException {
      ArrayList&lt;String&gt; output = new ArrayList&lt;String&gt;();
      String leftovers = string;
  
      if (regex.charAt(0) != '[' &amp;&amp; regex.charAt(regex.length() - 1) != ']') {
          int i = 0;
          while (!leftovers.isEmpty()) {
              if (i == leftovers.indexOf(regex)) {
                  if (!leftovers.substring(0, leftovers.indexOf(regex)).isEmpty()) {
                      output.add(leftovers.substring(0, leftovers.indexOf(regex)));
                  }
                  output.add(regex);
                  leftovers = leftovers.substring(i + regex.length());
                  i = 0;
              } else if (leftovers.indexOf(regex) == -1) {
                  output.add(leftovers);
                  leftovers = "";
              } else {
                  i++;
              }
          }
      } else {
          char[] regexChars = new char[regex.length() - 2];
          for (int i = 0; i &lt; regexChars.length; i++) {
              regexChars[i] = regex.charAt(i + 1);
          }
  
          int i = 0;
  
          for (int j = 0; j &lt; regexChars.length; j++) {
              while (!leftovers.isEmpty()) {
  
  
                  if (i == leftovers.indexOf(regexChars[j])) {
                      if (!leftovers.substring(0, leftovers.indexOf(regexChars[j])).isEmpty()) {
                          output.add(leftovers.substring(0, leftovers.indexOf(regexChars[j])));
                      }
                      output.add(Character.toString(regexChars[j]));
                      leftovers = leftovers.substring(i + 1);
                      i = 0;
                  } else if (leftovers.indexOf(regexChars[j]) == -1) {
                      output.add(leftovers);
                      leftovers = "";
                  } else {
                      i++;
                  }
              }
          }
      }
      return output.toArray(new String[0]);
  
  }       
  </code></pre>
  
  <p>The input arguments I am trying to pass in are "a?b?gf#e" and "[?#]".  However, the output I get is <code>[a, ?, b, ?, gf, null, e]</code>.  If I reverse the delimiters in regex as "[#?]", I get <code>[a, a?b?gf#e]</code>
  Could anyone tell me what I am doing wrong?  FYI I don't want to use the Pattern and Matcher classes, and we are not allowed to use the built-in split method at all.</p>