我有一个问题,需要将一个由数字组成的字符数组转换为整数并输出。
public static int ParseInt(char [] c) {
//convert to an int
return int;
}
数组的形式可能是这样的:
char [] c = {'3', '5', '9', '3'}
并将输出:
3593
我该如何做到这一点?
char[] c = {'3', '5', '9', '3'};
int number = Integer.parseInt(new String(c));
另一种方法是 -
public static int ParseInt(char [] c) {
int temp = 0;
for(int i = 0;i<c.length;i++) {
int value = Integer.parseInt(String.valueOf(c[i]));
temp = temp * 10 + value;
}
return temp;
}
int value = c[i] - '0'
。 - Morgan Patch这可能不是一个好的或标准的方法,但你可以将它作为其他解决方案。在下面的代码中,Arrays.toString(c)
将字符数组转换为字符串,然后用空白替换 [],'
,然后将字符串强制转换为 int 类型。
public static void main (String[] args) throws java.lang.Exception
{
char [] c = {'3', '5', '9', '3'};
String n=Arrays.toString(c).replace("[","").replace("]","").replace(",","").replace("'","").replace(" ","");
int k=Integer.parseInt(n);
System.out.println(k);
}
Arrays.toString()
将遍历数组的每个元素以创建字符串,然后每个replace
都会遍历相应字符串的字符数组中的每个元素。如果我没有误解什么,这种方法至少会遍历六个不同数组的每个元素。 - jasCharacter.getNumericValue()
函数。public static int ParseInt(char [] c) {
int retValue = 0;
int positionWeight = 1;
for(int i=c.lenght-1; i>=0; i--){
retValue += Character.getNumericValue(c[i]) * positionWeight;
positionWeight += 10;
}
return retValue;
}
length-1
开始循环,一直循环到0(根据位置权重约定)。因为它只包含数字。因此,我们可以这样解决:
int result = 0;
for (int i = 0; i < c.length; ++i) {
result = result * 10 + (c[i] - '0');
}
return result;