java string to int
时间: 2023-04-14 21:00:56 浏览: 72
Java中将字符串转换为整数可以使用Integer.parseInt()方法。例如:
String str = "123";
int num = Integer.parseInt(str);
这将把字符串"123"转换为整数123并存储在变量num中。需要注意的是,如果字符串无法转换为整数,将会抛出NumberFormatException异常。
相关问题
java string转int 手写
可以使用 Integer.parseInt() 方法将 String 转换为 int,示例代码如下:
public static int stringToInt(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= '0' && c <= '9') {
result = result * 10 + (c - '0');
} else {
throw new NumberFormatException("Invalid input: " + str);
}
}
return result;
}
这是一个手写的 stringToInt() 方法,它将一个 String 类型的参数转换为 int 类型的返回值。它使用了一个 for 循环来遍历字符串中的每个字符,如果字符是数字,则将其转换为 int 类型并添加到结果中,否则抛出一个 NumberFormatException 异常。
javastring转int数组的方法
可以使用String类的split()方法将字符串按照指定的分隔符分割成字符串数组,然后利用Integer类的parseInt()方法将每个字符串转换成int类型,最后将转换后的int类型放入int数组中。具体实现如下:
```java
public static int[] stringToIntArray(String str, String delimiter) {
String[] strArray = str.split(delimiter);
int[] intArray = new int[strArray.length];
for (int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
}
return intArray;
}
```
其中,str表示要转换的字符串,delimiter表示分隔符,比如逗号、空格、分号等。调用该方法可以将字符串转换成int数组,例如:
```java
String str = "1,2,3,4,5";
int[] intArray = stringToIntArray(str, ",");
```
这样就可以将字符串"1,2,3,4,5"转换成int数组[1, 2, 3, 4, 5]。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)