In Java, you can use the Stringtokennizer class to split a String into the different tokenas by defined delimiter. (Space is the default delimiter). Here ' re the StringTokennizer
examples:
Example 1
Uses StringTokennizer
to split a string by "space" and "comma" delimiter, and iterate the StringTokenizer elements and print it out O Ne by one.
PackageCom.mkyong;ImportJava.util.StringTokenizer; Public classApp { Public Static voidMain (string[] args) {String str= "This is a String, split by StringTokenizer, created by Mkyong"; StringTokenizer St=NewStringTokenizer (str); System.out.println ("----Split by Space------"); while(St.hasmoreelements ()) {System.out.println (st.nextelement ()); } System.out.println ("----Split by comma ', '------"); StringTokenizer St2=NewStringTokenizer (str, ","); while(St2.hasmoreelements ()) {System.out.println (st2.nextelement ()); } }}
Output
----Split by space------Thisisstring,splitbystringtokenizer,createdbymkyong----split by comma ', '------ This is a String split by StringTokenizer created by Mkyong
Example 2
Read a CSV file and use StringTokenizer to split the string by ' | ' delimiter, and print it out.
File:c:/test.csv
PackageCom.mkyong;ImportJava.io.BufferedReader;ImportJava.io.FileReader;Importjava.io.IOException;ImportJava.util.StringTokenizer; Public classReadFile { Public Static voidMain (string[] args) {bufferedreader br=NULL; Try{String line; BR=NewBufferedReader (NewFileReader ("Test.csv")); while(line = Br.readline ())! =NULL) {System.out.println (line); StringTokenizer StringTokenizer=NewStringTokenizer (line, "|"); while(Stringtokenizer.hasmoreelements ()) {Integer ID=Integer.parseint (Stringtokenizer.nextelement (). toString ()); Double Price=double.parsedouble (Stringtokenizer.nextelement (). toString ()); String username=stringtokenizer.nextelement (). toString (); StringBuilder SB=NewStringBuilder (); Sb.append ("\nid:" +ID); Sb.append ("\nprice:" +Price ); Sb.append ("\nusername:" +username); Sb.append ("\n*******************\n"); System.out.println (Sb.tostring ()); }} System.out.println ("Done"); } Catch(IOException e) {e.printstacktrace (); } finally { Try { if(BR! =NULL) Br.close (); } Catch(IOException ex) {ex.printstacktrace (); } } }}
Output
1| 3.29| 13.29Username: mkyong******************* 2| 4.345| 24.345Username: eclipse******************* Done
Java StringTokenizer Example