如何将 char [] 转换为 int?

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;
}

这可能不是一个好的或标准的方法,但您可以将它用作代码下面的其他 solution.In 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);
    }

DEMO

您可以使用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;

希望对您有所帮助。