Pages

Friday, May 16, 2014

Split function in Java

For ages I thought String.split() would work with any sort of delimiters in java. Un fortunately it has tough time working with delimiters as multiple string especially the one which i encountered "$|$"

 

It was confusing and irritating me for a while. God bless me, I am surrounded by sound techies. They introduced Mr.StringTokenizer to me. And so as a test attempt as always I wrote a split command in java using the same.

 

The good thing about this method is it does not depend on Regex. I believe it works well for most cases :)

 

public String[] split(String sourceString, String delimiter) {

 

  String returnArray[]=null;

  StringTokenizer strTknVrXML= new StringTokenizer(sourceString,delimiter);

 

  int tknItr=0;

  returnArray=new String[strTknVrXML.countTokens()];

 

  while (strTknVrXML.hasMoreElements()) {

    returnArray[tknItr++]=strTknVrXML.nextElement().toString();

  }

 

  return returnArray;

}

 

Hope this helps some one :)

 

 

No comments:

Post a Comment