Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

string split method

Status
Not open for further replies.

developerinlondon

Programmer
Jan 11, 2003
196
GB
I am trying to use the split method to split a string by '|' into an array of strings, the code looks like belwo:
Code:
String s = "first sentence|second sentence|third sentence";
String[] slist = s.split("|");

now if I want to iterate over slist I find that it put all the letters in individually, ie f, i, r, s, t,... etc.

any ideas how i can get it to split by bar? (i tried s.split("\|"), that doesnt compile.

thanks in advance.
 
thanks!
I was trying with the StringTokenizer also and got that working too -
Code:
       StringTokenizer url_list = new StringTokenizer(request.getParameter("urls"),"|");
        String[] urls = new String[url_list.countTokens()];
        for (int i = 0; i < urls.length;i++) {
                urls[i] = url_list.nextToken();
        }
however I found some benchmarks on the net that StringTokenizers works faster then split? Is this true in this case also? I seem to be getting the exact same result when I benchmark it. Maybe its something new in Java 5? Or am I better off with StringTokenizer for best performance?

thanks

 
When String.split() was introdcued in Java 1.4, Sun said that StringTokenizer should be avoided, and String.split() should be used.

Unless you're writing seriously tight code, use which one you feel more comfortable with. I doubt you'll ever see the difference, if there is any, between the two.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top