Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

String Splitter

0.00/5 (No votes)
9 Mar 2003 1  
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]);
  }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here