有许多方法可以将字符串转换为整数对象。在以下方法中,哪个是最有效的:
Integer.valueOf()
Integer.parseInt()
org.apache.commons.beanutils.converters.IntegerConverter
我的使用情况需要创建包装整数对象...也就是没有原始的int...并且转换后的数据用于只读。
有许多方法可以将字符串转换为整数对象。在以下方法中,哪个是最有效的:
Integer.valueOf()
Integer.parseInt()
org.apache.commons.beanutils.converters.IntegerConverter
我的使用情况需要创建包装整数对象...也就是没有原始的int...并且转换后的数据用于只读。
你好 - 我对Java比较新,所以请原谅我的无知。
我正在寻找一种将混合字符串(字母和数字)解析为INT的方法(有点像JavaScript的做法)。在JAVADOC文件中找不到任何相关内容,所以经过大量搜索,我编写了一个可以实现这个功能的函数:
// This function takes a string mixed with numbers and letters and returns an INT with
// the first occurrence of a number (INT) in said string, ignoring the rest;
// -- Basically, loop checks if char is a digit, if yes, puts digit back into new array, if no, puts a whitespace in its place
// this creates an array with only digits; By converting it to a string and then trimming whitespaces, it gets parsed into an INT
public static int mixedStringToInt (String str) {
boolean flag = true;
boolean isNumber = false;
final String refNumbers = "0123456789";
int strlen = str.length();
char[] numberArray = new char[strlen];
char[] stringArray = str.toCharArray();
for (int i = 0; i < strlen;i++){
if(refNumbers.indexOf(stringArray[i]) > 0 && flag){
// if current char is a digit
isNumber = true;
while (flag){
numberArray[i] = stringArray[i];
if(i+1 >= strlen || refNumbers.indexOf(stringArray[i+1]) < 0) flag = false;
i++;
}
} else {
// if current char is not a digit
numberArray[i] = ' ';
}
}
if (isNumber){
return Integer.valueOf(new String(numberArray).trim());
} else return 0;
}
除了我之外,这对任何人有用吗?我写这个是浪费时间吗,因为已经有一个可以做我想要的事情的方法了吗?