编写Java函数,用于将字符串转换为整数类型
发布时间:2023-06-29 17:36:21
下面是一个简单的Java函数,将字符串转换为整数类型:
public class StringToInt {
public static void main(String[] args) {
String str = "12345";
int num = stringToInt(str);
System.out.println(num);
}
public static int stringToInt(String str) {
int res = 0;
int sign = 1;
int i = 0;
// 处理正负号
if (str.charAt(0) == '-' || str.charAt(0) == '+') {
if (str.charAt(0) == '-') {
sign = -1;
}
i++;
}
// 遍历每个字符,并将其转换为整数
for (; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= '0' && c <= '9') {
int digit = c - '0';
// 判断是否超出整数范围
if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && digit > 7)) {
if (sign == 1) {
return Integer.MAX_VALUE;
} else {
return Integer.MIN_VALUE;
}
}
res = res * 10 + digit;
} else {
break;
}
}
return sign * res;
}
}
这个函数的实现思路如下:
1. 首先判断字符串是否有正负号,如果有,则确定符号,并将索引往后移动一位。
2. 遍历字符串的每个字符,如果是数字字符,则将其转换为数字并累加到结果中,否则退出循环。
3. 在累加过程中,如果结果超出了整数的范围,则根据符号返回对应的最大或最小整数值。
注意:
- 这个函数只能转换合法的整数字符串,对于非法字符串,例如含有非数字字符或超过整数范围的字符串,结果将不准确。
- 如果字符串为空或长度为0,则结果为0。
- 函数的时间复杂度为O(n),其中n是字符串的长度。
