如何将char []转换为int?

时间:2015-02-07 16:18:34

标签: java arrays char

我有一个问题,我需要取一个字符数组(仅由数字组成)并将其作为整数打印出来。

public static int ParseInt(char [] c) {
    //convert to an int
    return int;
}

数组看起来像这样:

char [] c = {'3', '5', '9', '3'}

并输出:

3593

我将如何做到这一点?

5 个答案:

答案 0 :(得分:7)

char[] c = {'3', '5', '9', '3'};
int number = Integer.parseInt(new String(c));

答案 1 :(得分:0)

替代方式将是 -

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

答案 2 :(得分:0)

它可能不是一个好的或标准的方法,但你可以使用它作为其他解决方案。在下面的代码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);
    }

DEMO

答案 3 :(得分:0)

您可以使用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(根据位置权重约定)。

答案 4 :(得分:0)

因为它只包含数字。因此,我们可以这样解决:

int result = 0;
for (int i = 0; i < c.length; ++i) {
    result = result * 10 + (c[i] - '0');
}
return result;

我希望它有所帮助。

相关问题