[英]How do I convert a char [] to an int?
我有一个问题,我需要采取一个字符数组(仅由数字组成)并将其值作为整数打印出来。
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;
}
它可能不是一个好的或标准的方法,但你可以使用它作为其他解决方案。在下面的代码Arrays.toString(c)
将字符数组转换为字符串,然后将[],'
替换为空,然后将类型转换为字符串。
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);
}
您可以使用Character.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;
我希望它有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.