parsing - 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 store information (capital, residents, area, capital) in different variables. how go parsing this? notice there spaces in names.

i have tried reading each token ( scanner.next() ) fails when there spaces in capital or country name.

i have tried reading each line , parsing can't figure out way parse correctly since there sometime spaces in names. (i used indexof() , substring() )

this part of bigger file there no spaces in residents or area field in 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); } 

i hope have multiline string per question title. why don't use regex whole content. given string stored in variable data

data.split("[ ]{2,}") 

this give array of data whole. when have parse can loop 4 elements @ time

(edit)

or else can use function... hope easier you.

list<map<string, string>> parse(string data){     list<map<string, string>> datalist = new arraylist<map<string, string>>();     string[] lines = data.split("\n");       string[] keys = lines[0].split("[ ]{2,}");     (int = 1; < lines.length; i++) {         string row[] = lines[i].split("[ ]{2,}");         map<string, string> rowmap = new hashmap<string, string>();         (int j = 0; j < row.length; j++) {             rowmap.put(keys[j], row[j]);         }         datalist.add(rowmap);     }     return datalist; } 

Comments

Popular posts from this blog

tcpdump - How to check if server received packet (acknowledged) -