file - Read the third string only java -


i have file example :

file.txt

milano tirana paris

madrid istanbul berlin

and want read third words of each line paris , berlin. tried substring won't work because length changes. how can ?

i'd recommend reading whole line, tokenizing splitting @ whitespace, , return index of value want.

something this:

package misc;  /**  * cityparser demo  * @author michael  * @link https://stackoverflow.com/questions/24420434/read-the-third-string-only-java/24420447#24420447  * @since 6/25/2014 8:36 pm  */ public class cityparser {      public static void main(string[] args) {         int tokenindex = 2;         cityparser parser = new cityparser();         (string arg : args) {             system.out.println((string.format("line: '%s' tokenindex: %d token: %s", args, tokenindex, parser.gettoken(arg, tokenindex))));         }     }      public string gettoken(string line, int tokenindex) {         string token = null;         if ((line != null) && (line.trim().length() > 0)) {             string [] tokens = line.split("\\s+");             if ((tokens.length > 0)) {                 token = tokens[tokenindex];             }         }         return token;     } } 

Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -