Java – Parse integer from string containing letters
This post shows you how to parse a string containing letters to an integer using Java.
1. First case: We only want to get an integer from the first digits of the string
Input (String) | Output (Integer) |
123abcd | 123 |
20.4fcdw31 | 20 |
15ab23 | 15 |
To do this, we need to use NumberFormat
class to parse a string to an integer. Here is the code example:
StringExample.java
package com.bytenota;
import java.text.NumberFormat;
import java.text.ParseException;
public class StringExample {
public static void main(String[] args) throws ParseException {
String str1 = "123abcd";
int result1 = NumberFormat.getInstance().parse(str1).intValue();
System.out.println(result1); // 123
String str2 = "20.4fcdw31";
int result2 = NumberFormat.getInstance().parse(str2).intValue();
System.out.println(result2); // 20
String str3 = "15ab23";
int result3 = NumberFormat.getInstance().parse(str3).intValue();
System.out.println(result3); // 15
}
}
2. Second case: We want to get an integer from the digits of the string
Input (String) | Output (Integer) |
123abcd | 123 |
20.4fcdw31 | 20431 |
15ab23 | 1523 |
We simply remove all non-digit characters from the string and then parse it to integer using Integer.parseInt
method as normal. Here is the code example:
StringExample.java
package com.bytenota;
import java.text.ParseException;
public class StringExample {
public static void main(String[] args) throws ParseException {
String str1 = "123abcd";
int result1 = Integer.parseInt(str1.replaceAll("\\D", ""));
System.out.println(result1); // 123
String str2 = "20.4fcdw31";
int result2 = Integer.parseInt(str2.replaceAll("\\D", ""));
System.out.println(result2); // 20431
String str3 = "15ab23";
int result3 = Integer.parseInt(str3.replaceAll("\\D", ""));
System.out.println(result3); // 1523
}
}