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

String Splitter

0.00/5 (No votes)
1 Nov 2001 1  
User defined StringTokenizer

Introduction

I got a problem where NULL values should also play a role in my program. But when I use StringTokenizer class to split, it eliminates null values, so I have written my own program that will help me to give null values.

import java.util.*;
public class Split
{
       public String[] split(String str,char x)
       {
               Vector v=new Vector();
               String str1=new String();
               for(int i=0;i<str.length();i++)
               {
                       if(str.charAt(i)==x)
                       {
                               v.add(str1);
                               str1=new String();
                       }
                       else
                       {
                               str1+=str.charAt(i);
                       }
               }
               v.add(str1);
               String array[];
               array=new String[v.size()];
               for(int i=0;i<array.length;i++)
               {
                       array[i]=new String((String)v.elementAt(i));
               }

               return array;
       }
       public static void main(String s[])
       {
               Split ss=new Split();
               String array[];
               array=ss.split(s[0],s[1].charAt(0));
               for(int i=0;i<array.length;i++)
               System.out.println(array[i]);                
       }
}

Example:

String str=”Koundinya,,”programmer”;
StringTokeizer st=new StringTokenizer(str);
Split ss=new Split();
String array[];
array=ss.split(str,’,’);

StringTokenizer will split this into Koundinya and programmer.

But Split.class gives result as Koundinya null and programmer.

I hope this program will help beginners.

History

  • 1st November, 2001: Initial post

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