RVP
RVP

Reputation: 45

How to parse an int from a string java?

I'm trying to parse an int from a dummy String for test reasons. The string will be:

String numOfStudents = "Number of Students: 5";

I want to parse this String, ensuring it contains the line 'Number of Students' as well as finding out the int value.

How can I achieve this? I need the int value to compare it to another int value.

Thanks

Upvotes: 2

Views: 1120

Answers (3)

Nightswatch
Nightswatch

Reputation: 143

String numOfStudents = "Number of Students: 55546";
int lastIndex = numOfStudents.lastIndexOf(" ");
if(lastIndex > -1 && lastIndex+1 < numOfStudents.length()) {
String num = numOfStudents.substring(lastIndex+1);
System.out.println(Integer.parseInt(num));
}

Upvotes: 1

roeygol
roeygol

Reputation: 5028

    final String NUM_OF_STUDENTS = "Number of Students: ";

    String numOfStudents = "Number of Students: 5";
    int lastIndex = numOfStudents.lastIndexOf(NUM_OF_STUDENTS);

    if (lastIndex != -1){
        String number = numOfStudents.substring((lastIndex + (NUM_OF_STUDENTS.length())) , numOfStudents.length());
        Integer yourResultNumber = Integer.parseInt(number);
        System.out.println(yourResultNumber);
    }

Upvotes: 2

Sarz
Sarz

Reputation: 1976

Since Integer cannot parse String values it throws NumberFormatException because numbers are expected as input, I would suggest you as you have static type of Strings use like this:

String numOfStudents = "Number of Students: 5";
String[] p = numOfStudents.split(":");

Integer i= Integer.parseInt(p[1].trim());
System.out.println(i);

As, p[0] contain String (label) and p[1] contain its value. You can use it later if you want.

Upvotes: 1

Related Questions