aspose file tools*
The moose likes Beginning Java and the fly likes StringTokenizer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "StringTokenizer" Watch "StringTokenizer" New topic
Author

StringTokenizer

francis varkey
Ranch Hand

Joined: Sep 13, 2005
Posts: 169

I have a string , String str="~~20";.
Can I tokenize this string using StringTokenizer or using spilt() method String class. I need the out put like.

String id="", String name="", String age=20;

Thanks in advance
Francis
bhagya hari
Greenhorn

Joined: Oct 15, 2008
Posts: 5
You can use stringTokenizer if you use the "~" as separator for the id and name.
Manoj Maniraj
Ranch Hand

Joined: Mar 25, 2009
Posts: 38
Java API recommends not to use StringTokenizer any more

There are empty strings are indicated by the ~ with nothing between them that's a lot more work with a StringTokenizer. By default it gives you just "20", and skips the empties. You can use a special constructor that takes a boolean to tell the StringTokenizer to return delimiters, but that gets complicated too.

It's much easier to use split("~"), which immediately returns {"", "", "20"}


Cheers..


http://manojmaniraj.blogspot.com
francis varkey
Ranch Hand

Joined: Sep 13, 2005
Posts: 169
"~" is my delimiter.
Manoj Maniraj
Ranch Hand

Joined: Mar 25, 2009
Posts: 38
Yes
francis varkey
Ranch Hand

Joined: Sep 13, 2005
Posts: 169
1)
String id="";
String name="";
String age="";
String str="~~20";
try{
StringTokenizer stkn=new StringTokenizer(str,"~");
id=stkn.nextToken();
name=stkn.nextToken();
age=stkn.nextToken();

System.out.println(id);
System.out.println(name);
System.out.println(age);

}
catch(Exception ex){
ex.printStackTrace();
}

this will give exception

2)

String id="";
String name="";
String age="";
String str="101~~";
try{
String ar[]=str.split("~");
id=ar[0];
name=ar[1];
age=ar[2];

System.out.println(id);
System.out.println(name);
System.out.println(age);

}
catch(Exception ex){
ex.printStackTrace();
}

this will also give the exception.

How to handle such situations ?



Piet Verdriet
Ranch Hand

Joined: Feb 25, 2006
Posts: 266
francis varkey wrote: ...

this will also give the exception.

How to handle such situations ?



Use:

francis varkey
Ranch Hand

Joined: Sep 13, 2005
Posts: 169
Thank You. It is working fine.
Piet Verdriet
Ranch Hand

Joined: Feb 25, 2006
Posts: 266
francis varkey wrote:Thank You. It is working fine.


You're welcome.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: StringTokenizer