Splits a String based on a single character - Android java.lang

Android examples for java.lang:Character

Description

Splits a String based on a single character

Demo Code

import java.util.ArrayList;
import java.util.List;

public class Main {

  /**/*from   w  ww  .j  a  va2  s.com*/
   * Splits a String based on a single character, which is usually faster than
   * regex-based String.split().
   */
  public static String[] fastSplit(String string, char delimiter) {
    List<String> list = new ArrayList<String>();
    int size = string.length();
    int start = 0;
    for (int i = 0; i < size; i++) {
      if (string.charAt(i) == delimiter) {
        if (start < i) {
          list.add(string.substring(start, i));
        } else {
          list.add("");
        }
        start = i + 1;
      } else if (i == size - 1) {
        list.add(string.substring(start, size));
      }
    }
    String[] elements = new String[list.size()];
    list.toArray(elements);
    return elements;
  }

}

Related Tutorials