简体   繁体   中英

can you make a sort of column in txt file java

I have a text file that contains lines like the following:

00001:dexter:1989:9

In other words, each line contains fields where the field delimiter is the colon character ( : ). Is there any way to access each field and get, for example, dexter as a string? I've tried using method useDelimeter() and then reading the first line but it's not a string. This is the program:

Scanner sc;
String token=null;
sc = new Scanner("00001:dexter:1989:9");
sc.useDelimiter(":");
while (sc.hasNext()) {
    token = sc.next();
    System.out.println(token);
}
System.out.println(ss.substring(0, ss.indexOf(":")));

Is there a way to read any field as a string anytime?
I'm new to java and new to SO so any answer will be appreciated. Thank you.

The easiest method I can think of is :

String getColumn(int n,string s)
{
   return ( n <= 0 ) ? s.subString(0,s.indexOf(":")) : getColumn(--n,s.subString(s.indexOf(":") + 1 , s.length);
}

getColumn(1,"00001:dexter:1989:9"); // Returns dexter

This function recursively splits the string until the required column is the column it starts with. Then it splits that column and returns it.


Input a:b:c , n = 1

  • Step 1 -> b:c
  • Step 2 -> b

That is in short it removes columns from the front until n > 0 and then removes all columns from the back leaving only the required column.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM