-4

I am currently using StringTokennizer class to split a String into different tokenas by defined delimiter

 public class App {  
        public static void main(String[] args) {  

            String str = "This is String , split by StringTokenizer, created by saral";  
            StringTokenizer st = new StringTokenizer(str);  


            System.out.println("---- Split by comma ',' ------");  
            StringTokenizer st2 = new StringTokenizer(str, ",");  

            while (st2.hasMoreElements()) {  
                System.out.println(st2.nextElement());  
            }  
        }  
    } 

Please advise me more alternative ways to achieve this as jdk 5 support scanner and java .util, regex....!! please advise..!!

Taryn
  • 242,637
  • 56
  • 362
  • 405
dghtr
  • 561
  • 3
  • 6
  • 20

3 Answers3

2

You could use java.lang.String.split() method:

String str = ...;
String[] tokens = str.split(",");

for (String s: tokens)
{
    System.out.println(s);
}
hmjd
  • 120,187
  • 20
  • 207
  • 252
0

You can just use String.split.

String str = "This is String , split by StringTokenizer, created by saral";
String[] arr = str.split(",");

Now, arr will be an array containing each comma-separated part of str.

kba
  • 19,333
  • 5
  • 62
  • 89
  • Can I use Scanner class also , to achieve the same thing...!! I was trying this.... public class App1 { public static void main(String[] args) { Scanner scanner = new Scanner("This is String , split by StringTokenizer, created by saral").useDelimiter(", "); while (scanner.hasNextLine()) ; System.out.println(scanner.nextLine()); } } I was trying these but not getting the result ..!!please advise..!! – dghtr Apr 06 '12 at 16:17
0

StringTokenizer is deprecated for all practical purposes, it's there only for backwards compatibility. Use the method split() instead, like this:

String[] splitted = str.split(",");

Now the returned String[] will contain the tokens.

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • I was looking for java regex or something new ,I want to avoid string split method and tokenizer some thing new from regex..!! – dghtr Apr 06 '12 at 16:20
  • @SARAL read the documentation of `split()` in the link, it receives a regular expression as a parameter! in this simple example `","` is a regex, but it can be as complex as you want – Óscar López Apr 06 '12 at 16:31