File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Reading from String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Reading from String" Watch "Reading from String" New topic

Reading from String

Tekaistu Tunnus

Joined: Apr 11, 2006
Posts: 3

I have a program that reads lines from a file. I save the lines to the String rivi. The problem is that one line contains 2 short Strings, one double and one integer. I need them separately, so how do separate them from that String?

For example, I have a String longString that contains the following data:
sukunimi etunimi 12345 52.415

I would like to save them in separate variables:
String shortString1 = sukunimi
String shortString2 = etunimi
int number1 = 12345
double number2 = 52.415
marc weber

Joined: Aug 31, 2004
Posts: 11343

Welcome to JavaRanch!

Take a look at the split method in java.lang.String. This will split your String into an array of separate String objects, which you can then work with (e.g., parse as primitive values).
[ April 11, 2006: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Sanjaya Sugiarto
Ranch Hand

Joined: Mar 25, 2004
Posts: 229
other alternative: look at StringTokenizer (java.util.StringTokenizer)

<a href="" target="_blank" rel="nofollow">Business Information Technology - Hochschule Furtwangen University, Germany</a>
Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
And when you're looking at the API doc for StringTokenizer, note the sentence
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.

Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
This may get us tossed out of the beginner forum, but if you get all those options down cold, peek at the JavaDoc for Scanner. It can read from a file and parse the lines into variables of the proper type all at once. If it looks too advanced, stick with split() and just file the name away for another day.

Let us know how you work this out!

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: Reading from String
It's not a secret anymore!