简体   繁体   中英

Reading Strings from lines in Java

I have a txt file formatted like:

Name 'Paul' 9-years old

How can I get from a "readline":

String the_name="Paul"

and

int the_age=9

in Java, discarding all the rest?

I have:

  ...       
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    StringBuffer stringBuffer = new StringBuffer();
    String line;
    while ((line = bufferedReader.readLine()) != null) {

       //put the name value in the_name

       //put age value in the_age

    }
...

Please suggest, thanks.

As you're using BufferedReader and everything is on the one line, you would have to split it to extract the data. Some additional formatting is then required to remove the quotes & extract the year part of age. No need for any fancy regex:

String[] strings = line.split(" ");
if (strings.length >= 3) {
   String the_name= strings[1].replace("'", "");
   String the_age = strings[2].substring(0, strings[2].indexOf("-"));
}

I notice you have this functionality in a while loop. For this to work, make sure that every line keeps the format:

text 'Name' digit-any other text
    ^^    ^^     ^

Important chars are

  • Spaces: min of 3 tokens needed for split array
  • Single quotes
  • - Hyphen character

use java.util.regex.Pattern:

Pattern pattern = Pattern.compile("Name '(.*)' (\d*)-years old");
for (String line : lines) {
    Matcher matcher = pattern.matcher(line);
    if (matcher.matches()) {
        String theName = matcher.group(1);
        int theAge = Integer.parseInt(matcher.group(2));
    }
}

You can use the String.substring , String.indexOf , String.lastIndexOf , and Integer.parseInt methods as follows:

String line = "Name 'Paul' 9-years old";
String theName = line.substring(line.indexOf("'") + 1, line.lastIndexOf("'"));
String ageStr = line.substring(line.lastIndexOf("' ") + 2, line.indexOf("-years"));
int theAge = Integer.parseInt(ageStr);
System.out.println(theName + " " + theAge);

Output:

Paul 9

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