Click here to Skip to main content
Licence CPOL
First Posted 9 Mar 2003
Views 39,576
Bookmarked 4 times

String Splitter

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

About the Author

Wee Ding

Web Developer

Singapore Singapore

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralA few comments PinmemberRyan Binns4:26 5 Jul '03  
GeneralAlready exists in JDK PinmemberRui "viZual" Lopes7:35 10 Mar '03  
GeneralRe: Already exists in JDK PinmemberJoe Billy18:26 12 Oct '03  

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

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 10 Mar 2003
Article Copyright 2003 by Wee Ding
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid