mercredi 1 avril 2015

How to parse this information from a string?


country residents area capital
Andorra 71201 468 Andorra la Vella
Italien 58133509 301230 Rom
San Marino 29251 61 San Marino


I need to store the information (capital, residents, area, capital) in different variables. How would I go about parsing this? Notice that sometimes there are spaces in the names.


I have tried reading each token ( scanner.next() ) this fails when there are spaces in the capital or country name.


I have tried reading each line and then parsing it but I can't figure out a way to parse everything correctly since there are sometime spaces in the names. (I used indexOf() and substring() )


This is part of a bigger file but there are no spaces in the residents or area field in the entire field.


My try:



while(scanner.hasNext()){

String info = scanner.nextLine();
//parse string
int nameindex = info.indexOf(" ");
System.out.println(info.substring(0,nameindex));
int resindex = info.indexOf(" ", nameindex);
}

Aucun commentaire:

Enregistrer un commentaire