Search code examples
stringsubstringtrimparseint

How can I get an integer out of a String with sections


I try to get an integer (right after "PLAYING:STATION\nID:"out of the String shown in my screenshot by using the following code:

 int zahl = Integer.parseInt(sentence.substring(sentence.indexOf("PLAYING:STATION\n
ID:")+1).trim());

But all I get is a NumberFormatException. How can I tell the trim()-method that it has to stop right after the number?

Screenshot of the complete String


Solution

  • Since you must select a specific ID: entry among several ones, I think the best way to proceed is using a regular expression. Using your output sample, I wrote the following code:

    String text = "PLAYING_MODE\nID:\nPLAYING:STATION\nID:2\nNAME:wazee.org";
    Pattern p = Pattern.compile("PLAYING:STATION\nID:(\\d+)");
    Matcher m = p.matcher(text);
    if (m.find()) {
      int number = Integer.parseInt(m.group(1));
      System.out.println(number);
    }
    

    which correctly parses the ID number that immediately follows PLAYING_STATION.

    You could as well repeatedly work with the overloaded String.indexOf() method (find PLAYING:STATION, then the following ID:, then the following \n). I think the code might be harder to read, but it would still do the job.

    I hope this will be helpful...

    Cheers,

    Jeff