Click here to Skip to main content
15,897,371 members
Articles / Programming Languages / Java / Java SE

String Splitter

Rate me:
Please Sign up or sign in to vote.
1.07/5 (16 votes)
9 Mar 2003CPOL 108.6K   4   3
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.

Java
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Singapore Singapore
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralA few comments Pin
Ryan Binns5-Jul-03 4:26
Ryan Binns5-Jul-03 4:26 
GeneralAlready exists in JDK Pin
Rui Dias Lopes10-Mar-03 7:35
Rui Dias Lopes10-Mar-03 7:35 
GeneralRe: Already exists in JDK Pin
xxrl12-Oct-03 18:26
xxrl12-Oct-03 18:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.