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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String Split() function

Status
Not open for further replies.

patnim17

Programmer
Jun 19, 2005
111
US
Hi,
Is there a function called split() that I can use to split a string by a delimiter in Java?

pat
 
Hi,
When I try this simple program..it throws a :
"Exception in thread "main" java.lang.NoSuchMethodError"
during run time...


import java.util.*;
import java.lang.*;


public class TestParseURL {
public static void main(String args[]) {
String str="t3://156.30.228.1,156.30.228.6:19002";
String strArr[] = str.split(",");
System.out.println(strArr[0] + "---" + strArr[1]);
}
}
 
This has nothing to do with your error, but you don't need to import java.lang. It's automatically done.

The split method came with JDK 1.4. If you have a prior version, it won't work.

If that's the case, I'd suggest taking a look at StringTokenizer class.

Cheers,
Dian
 
I Agree fully on the StringTokenizer idea. It was stated somewhere that the tokenizer is actually the prefered way to doing it.


An example:

Code:
import java.util.StringTokenizer;

public class test
{
  public static voic main (String args[])
  {
    String str = "123.123.123.123,123.123.123.123";
    StringTokenizer token = new StringTokenizer(str, ",");
    while(token.hasMoreTokens())
      System.out.println(token.nextToken());
  }
}
 
Aradon, StringTokenizer is NOT the preferred method of breaking strings up - the String.split() method is.

From the API doc you actually posted :
API said:
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Although no one still provided a reason for that ...

Cheers,
Dian
 
Doh! I had it backwards. Well. That's okay. We all make mistakes. :p
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top