Search code examples
javastringsplitparseint

why doesn't Integer.parseInt method work for splitted strings?


I'm trying to extract numbers from strings with specific format using String split method . then i want to get the numbers as int type using Integer parseInt method . here is a sample code which doesn't work . can somebody help me with this please?

String g = "hi5hi6";

String[] l = new String[2];
l = g.split("hi");

for (String k : l) {
    int p=Integer.parseInt(k);
    System.out.println(p);
}

I get this error :

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at com.company.Main.main(Main.java:36)

Solution

  • The issue here is likely that the String#split is leaving your array with one or more empty elements. Just filter those out and it should work:

    String g = "hi5hi6";
    String[] parts = g.split("hi");
    
    for (String part : parts) {
        if (!part.isEmpty()) {
            int p = Integer.parseInt(part);
            System.out.println(p);
        }
    }
    

    This prints:

    5
    6