Reputation: 23
I have a string that I want to read line by line:
"8688642986379252 Michael_Thompson 816 2500.0
8904000405634912 Barbara_Martin
8610835007621519 Charles_Jackson 1019 52800.0"
It goes on on and on in that format.
I tried separating it using for loops, charAt() and reducing the size of the string using substring() but I failed miserably.
I'm sure it's something simple but I just can't get it. Any ideas?
Upvotes: 0
Views: 66
Reputation: 85779
Use Scanner
to read line by line using nextLine
. Then, split every String
by blank space" "
:
Scanner scanner = new Scanner(stringWithBreaklines);
while (scanner.hasNext()) {
String line = scanner.nextLine();
String[] content = line.split(" ");
//do what you want/need with content
}
If the String
is inside a file, then read the file directly using Scanner
:
Scanner scanner = new Scanner(new File("file.txt"));
//same code as above...
Upvotes: 0
Reputation: 35598
I would suggest using str.split("\n")
. It will produce an array of strings, one index for each line. This is assuming you can read the whole thing into a string. If the input is large, this won't work.
Upvotes: 4
Reputation: 7271
Use the java.util.Scanner
class to read tokens one by one.
http://docs.oracle.com/javase/tutorial/essential/io/scanning.html
Upvotes: 0