PeacefulCalamity
PeacefulCalamity

Reputation: 23

How do I separate a string like this line by line?

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

Answers (3)

Luiggi Mendoza
Luiggi Mendoza

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

Chris Thompson
Chris Thompson

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

metacubed
metacubed

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

Related Questions