วิธีการแปลงสตริงเป็น Int ใน Java? หากสตริงมีเฉพาะตัวเลข วิธีที่ดีที่สุดในการแปลงสตริงเป็น Int คือการใช้ Integer.parseInt() หรือ Integer.valueOf() .
หากสตริงมีทั้งตัวเลขและอักขระ เราต้องใช้นิพจน์ทั่วไปเพื่อแยกตัวเลขออกจากสตริง จากนั้นแปลงสตริงที่เป็นผลลัพธ์เป็น Int
สิ่งหนึ่งที่ควรทราบคือ parseInt(String) คืนค่า int ดั้งเดิม ในขณะที่ valueOf(String) ส่งกลับวัตถุ Integer()
แปลงสตริงเป็น Int ใน Java
การใช้ Integer.parseInt()
public class ConvertStringToInt {
public static void main(String[] args) {
String stringNumber = "1234";
int number = convertStringToInt(stringNumber);
System.out.println(number);
}
private static int convertStringToInt(String number) {
return Integer.parseInt(number);
}
}
เอาท์พุต:
1234
การใช้ Integer.valueOf()
public class ConvertStringToInt {
public static void main(String[] args) {
String stringNumber = "1234";
int number = convertStringToInt(stringNumber);
System.out.println(number);
}
private static int convertStringToInt(String number) {
return Integer.valueOf(number);
}
}
เอาท์พุต:
1234
เป็นสิ่งสำคัญที่จะต้องทราบว่าหากสตริงมีอักขระและตัวเลข เช่น “1234abcd” ตัวแยกวิเคราะห์จำนวนเต็มจะส่ง NumberFormatException ตามที่ระบุไว้ใน Javadoc
ที่เกี่ยวข้อง:
- เหตุใดจึงแทนที่ toString() ใน Java
- วิธีย้อนกลับสตริงใน Java
- วิธีดึงตัวเลขออกจากสตริง
- วิธีเปรียบเทียบสตริงใน Java
การใช้ Integer.decode()
นอกจากนี้เรายังสามารถใช้ Integer.decode() . คุณลักษณะที่น่าสนใจของ decode คือสามารถแปลงเป็นฐานอื่นได้ เช่น base 10 , base 16 , ฯลฯ…
public class ConvertStringToInt {
public static void main(String[] args) {
String stringNumber = "1234";
int number = convertStringToInt(stringNumber);
System.out.println(number);
}
private static int convertStringToInt(String number) {
return Integer.decode(number);
}
}
เอาท์พุต:
1234
คลาส Apache Commons NumberUtils
สุดท้ายแต่ไม่ท้ายสุด เราสามารถใช้คลาส Apache Commons NumberUtils เพื่อแปลงสตริงเป็น Int ใน Java
สิ่งที่คุณต้องทำคือต้องมีการพึ่งพาต่อไปนี้ใน pom.xml . ของคุณ ไฟล์
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
จากนั้น คุณสามารถใช้:
import org.apache.commons.lang3.math.NumberUtils;
public class ConvertStringToInt {
public static void main(String[] args) {
String stringNumber = "1234";
int number = convertStringToInt(stringNumber);
System.out.println(number);
}
private static int convertStringToInt(String number) {
return NumberUtils.toInt(number);
}
}
เอาท์พุต:
1234