在Java中将int转换为数组char

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19237516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:19:38  来源:igfitidea点击:

Convert int to array char in Java

java

提问by Fertk Omr

I'm trying to convert a integer number to an array of chars without using String operations.

我试图在不使用字符串操作的情况下将整数转换为字符数组。

My attempt was:

我的尝试是:

int number = 12;
char[] test = Character.toChars(number);

for (char c : test)
    System.out.println(c);

There is no output, and should give me:

没有输出,应该给我:

'1'

'1'

'2'

'2'

How can I fix this? Thank you!

我怎样才能解决这个问题?谢谢!

采纳答案by arshajii

Try something like this:

尝试这样的事情:

int number = 12345;

char[] arr = new char[(int) (Math.log10(number) + 1)];

for (int i = arr.length - 1; i >= 0; i--) {
    arr[i] = (char) ('0' + (number % 10));
    number /= 10;
}

System.out.println(Arrays.toString(arr));
[1, 2, 3, 4, 5]

Note that floor(log10(n) + 1)returns the number of digits in n. Also, if you want to preserve your original number, create a copy and use that in the for-loop instead.

请注意,返回 中的位数。此外,如果您想保留原始号码,请创建一个副本并在-loop 中使用它。floor(log10(n) + 1)nfor

Also note that you might have to adapt the code above if you plan on also handling non-positive integers. The overall idea, however, should remain the same.

另请注意,如果您还计划处理非正整数,则可能需要修改上面的代码。但是,总体思路应该保持不变。

回答by nj-ath

Extract each digit of the number, convert it into a character(by adding '0') and store them into a char array. Let us know what you have tried.

提取数字的每个数字,将其转换为字符(通过添加“0”)并将它们存储到字符数组中。让我们知道您的尝试。

回答by Dawood ibn Kareem

char[] test = Integer.toString(number).toCharArray();

char[] test = Integer.toString(number).toCharArray();

回答by Prateek

+1 for @arshajii's code log10(n) + 1is something new for me as well. If you intend to use Vectorsinstead of arraysyou can also follow this procedure(But the Vector has elements in reverse order) in which you never need to calculate the size of number itself

+1 @arshajii 的代码log10(n) + 1对我来说也是新的。如果你打算使用Vectors而不是arrays你也可以按照这个过程(但向量具有相反顺序的元素),你永远不需要计算数字本身的大小

public static Vector<Character> convert(int i) {
        Vector<Character> temp = new Vector<Character>();
        while (i > 0) {
            Character tempi = (char) ('0' + i % 10);
            i = i / 10;
            temp.add(tempi);
        }
        return temp;
    }