如何在 Java 中把一個字串轉換為一個整型 int
Mohammad Irfan
2023年10月12日
Java
Java String
Java Integer
-
在 Java 中使用
parseInt()將字串String轉換為整型int -
在 Java 中使用
Apache將String轉換為int -
使用 Java 中的
decode()將String轉換為int -
使用 Java 中的 valueOf()
將String 轉換為int -
在 Java 中使用
parseUnsignedInt()將String轉換為int -
在 Java 中使用
replaceAll()刪除非數字字元後轉換字串
本教程介紹瞭如何在 Java 中把一個字串 String 轉換成一個整型 int,並列舉了一些示例程式碼來理解它。
在 Java 中使用 parseInt() 將字串 String 轉換為整型 int
String 和 int 都是 Java 中的資料型別。String 用於儲存文字資訊,而 int 用於儲存數字資料。
在這裡,我們使用 Integer 類的 parseInt() 方法,返回一個 Integer。由於 Java 做了隱式自動裝箱,那麼我們可以將其儲存成 int 基元型別。請看下面的例子。
public class SimpleTesting {
public static void main(String[] args) {
String str = "1234";
int int_val = Integer.parseInt(str);
System.out.println(int_val);
}
}
輸出:
1234
在 Java 中使用 Apache 將 String 轉換為 int
如果你正在使用 Apache 庫,你可以使用 NumberUtils 類的 toInt() 方法返回一個 int 值。如果傳遞的字串中包含任何非數字字元,這個方法不會丟擲任何異常,而是返回 0。使用 toInt() 比使用 parseInt() 是安全的,因為 parseInt() 會丟擲 NumberFormatException。請看下面的例子。
import org.apache.commons.lang3.math.NumberUtils;
public class SimpleTesting {
public static void main(String[] args) {
String str = "1234";
int int_val = NumberUtils.toInt(str);
System.out.println(int_val);
str = "1234x"; // non-numeric string
int_val = NumberUtils.toInt(str);
System.out.println(int_val);
}
}
輸出:
1234
0
使用 Java 中的 decode() 將 String 轉換為 int
我們可以使用 Integer 類的 decode() 方法從一個字串中獲取 int 值。它返回 Integer 值,但如果你想得到 int(基本)值,則使用 intValue() 和 decode() 方法。請看下面的例子。
public class SimpleTesting {
public static void main(String[] args) {
String str = "1424";
int int_val = Integer.decode(str);
System.out.println(int_val);
// int primitive
int_val = Integer.decode(str).intValue();
System.out.println(int_val);
}
}
輸出:
1424
使用 Java 中的 valueOf()將String 轉換為 int
我們可以使用 valueOf() 方法來獲取一個字串轉換後的 int 值。
public class SimpleTesting {
public static void main(String[] args) {
String str = "1424";
int int_val = Integer.valueOf(str);
System.out.println(int_val);
}
}
1424 1424
在 Java 中使用 parseUnsignedInt() 將 String 轉換為 int
如果我們要轉換一個不包含符號的字串,使用 parseUnsignedInt() 方法來獲取 int 值。它對無符號字串的值工作正常,如果值是有符號的,則會丟擲一個異常。
public class SimpleTesting {
public static void main(String[] args) {
String str = "1424";
int int_val = Integer.parseUnsignedInt(str);
System.out.println(int_val);
}
}
輸出:
1424
在 Java 中使用 replaceAll() 刪除非數字字元後轉換字串
如果字串中包含非數字字元,則使用 String 類的 replaceAll() 方法與 regex 刪除所有非數字字元,然後使用 Integer 類的 parseInt() 方法得到其等價的整數值。請看下面的例子。
public class SimpleTesting {
public static void main(String[] args) {
String str = "1424x";
str = str.replaceAll("[^\\d]", "");
int int_val = Integer.parseInt(str);
System.out.println(int_val);
}
}
輸出:
1424
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
相關文章 - Java String
- 如何在 Java 中以十六進位制字串轉換位元組陣列
- 如何在 Java 中執行字串到字串陣列的轉換
- 如何將 Java 字串轉換為位元組
- 如何從 Java 中的字串中刪除子字串
- 用 Java 生成隨機字串
- Java 中的交換方法