65.9K
CodeProject is changing. Read more.
Home

String Splitter

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.07/5 (14 votes)

Mar 10, 2003

CPOL
viewsIcon

108802

A user defined String Tokenizer (Java).

Introduction

This is a simple program to split a string by providing a delimiter string. I met problems when I wanted to use a delimiter like "[XX]" with the JDK Split function, hence I wrote a simple one here. This material is mainly for beginners. I published this right after I wrote it, hence I haven't double checked this code thoroughly, but I suppose the strSplit function should be working perfectly.

public class StrSplit { 

  public static String[] strSplit (String _str, String _x) {
    Vector _v = new Vector();
    String _stmp = new String();
    int i=0,j=0,cnt=0;
    while ((i=_str.indexOf(_x,i))!=-1) {
      cnt++;
      if (cnt%2==1) {
        i = j = i+_x.length();
        continue;
      }
      _stmp = _str.substring(j,i);
      _v.add(_stmp);
      _stmp = new String();
      j = i+_x.length();
    }
    if (j < _str.length()-1) {
      _stmp = _str.substring(j,_str.length());
      _v.add(_stmp);
    }
    String[] _array = new String[_v.size()];
    for (int k=0;k<_array.length;k++)
      _array[k] = new String(((String)_v.elementAt(k)).trim());
    return _array;
  } 

  /** Test **/
  public static void main(String s[]) {
    StrSplit tt=new StrSplit();
    String array[];
    array=tt.strSplit("[STR] Rank bagus manis [STR] Grade A CC BBB","[STR]");
    for(int i=0;i<array.length;i++)
    System.out.println(array[i]);
  }
}