Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reading from String

 
Tekaistu Tunnus
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Sanjaya Sugiarto
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
other alternative: look at StringTokenizer (java.util.StringTokenizer)
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic