-2

I have a String that looks like this:

String meta = "1 \n"
    + "Herst \n"
    + "01 Jan 2019 – 31 Dec 2020 \n"
    + "01 Jan 2020 \n"
    + "CONFIG \n"
    + "XML \n"
    + "AES \n"
    + "RSA \n"
    + "256 \n"
    + "16 \n"
    + "128 \n";

What is the smartest way if I want to read a specific line out of this String in Java?

For example, I need in another part of my code the number of the second last line (in this case it's 16). How can I read this number out of the String?

khelwood
  • 55,782
  • 14
  • 81
  • 108
aslanj
  • 71
  • 6

1 Answers1

3

If it's already in String form, just split it into lines using \n as a delimiter to get an array of lines:

String[] lines = meta.split("\n");

Then you can easily get a specific line. For instance, System.out.println(lines[9]) will print 16.

If you need the 16 in the form of an int, you'd need to remove the whitespaces around it, and parse it:

int parsed = Integer.parseInt(lines[9].trim());

Malt
  • 28,965
  • 9
  • 65
  • 105