So I've got this String with book information:
String data = "Harry Potter 1 | J.K. Rowling| 350 | Fantasy | Hunger Games | Suzanne Collins | 500 | Fantasy | The KingKiller Chronicles | Patrick Rothfuss | 400 | Heroic Fantasy"
Then I split the String:
String splitData = data.split("\\|");
This will cause Harry Potter 1 to be in position 0, JK Rowling to be in position 1, 350 to be in position 2, etc.
You might see a pattern in here, which is the fact that at position 0 is a title of a book, at position 1 is the author, at position 2 is the amount of pages and at position 3 is the genre. Then it starts again at position 4, which is again the title of a book, position 5 being the Author of the book, etc etc. I assume that you understand where I'm going.
Now let's say that I want to display all those elements separately, like printing all the titles apart, all the authors, all the amount of pages, etc. How would I accomplish this?
This should be possible to do since the titles are in 0, 4, 8. The authors are in 1, 5, 9, etc.
String data = "Harry Potter 1 | J.K. Rowling| 350 | Fantasy | Hunger Games | Suzanne Collins | 500 | Fantasy | The KingKiller Chronicles | Patrick Rothfuss | 400 | Heroic Fantasy";
String[] splitData = data.split("\\|");
for(int i=0; i<splitData.length;i++) {
if(i % 4 == 0) System.out.println("Title: "+splitData[i]);
else if(i % 4 == 1) System.out.println("Author: "+splitData[i]);
else if(i % 4 == 2) System.out.println("Pages: "+splitData[i]);
else if(i % 4 == 3) System.out.println("Genre: "+splitData[i]);
}
Difficult, isnt it?
You can recall that for
loop lets you perform any modifications in the last expression, not only i++
. For this case, you can use i += 4
. Then in each iteration the name will ne at splitData[i]
, the author at splitData[i+1]
, the number of pages at splitData[i+2]
, and the genre at splitData[i+3]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.