java 如何将数字字符串拆分为int数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28008730/
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
How to split string of numbers in to int array?
提问by priyank
How to split string containing numbers into int array i.e
如何将包含数字的字符串拆分为 int 数组,即
String s="12345";
int i[]=new int[5];
i[0]=1;
i[1]=2;
i[2]=3;
i[3]=4;
i[4]=5;
i have tried it by
我已经试过了
String s="12345";
int i[]=new int[5];
int tem = Integer.parseInt(s);
for(int t=0;t<5;t++){
i[4-t]=tem%10;
tem=tem/10;
}
it is giving right answer in above case but in case of String s="73167176531330624919225119674426574742355349194934"it fails so any other way or how to use split methodin above case
它在上述情况下给出了正确答案,但在String s="73167176531330624919225119674426574742355349194934" 的情况下, 它失败了,所以任何其他方式或如何在上述情况下使用拆分方法
回答by stanga bogdan
You can use Character.getNumericValue(char)
您可以使用Character.getNumericValue(char)
String str = "12345";
int[] nums = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
nums[i] = Character.getNumericValue(str.charAt(i));
}
回答by SMA
That's because your number wont fit in the integer range nor in long range. Also to note, Your code wont be that efficient due to division and modulas operator as well. Instead you could always use charAtapi of String and convert individual characters to a number as give below:
那是因为您的数字既不适合整数范围,也不适合长范围。另请注意,由于除法和模运算符,您的代码也不会那么高效。相反,您始终可以使用String 的charAtapi 并将单个字符转换为数字,如下所示:
String s = "73167176531330624919225119674426574742355349194934";
int[] numbers = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
numbers[i] = s.charAt(i) - '0';
}
System.out.println(Arrays.toString(numbers));
Output:
[7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9, 2, 2, 5, 1, 1, 9, 6, 7, 4, 4, 2, 6, 5, 7, 4, 7, 4, 2, 3, 5, 5, 3, 4, 9, 1, 9, 4, 9, 3, 4]
回答by Rohit Jain
The culprit is this line of code:
罪魁祸首是这行代码:
int tem = Integer.parseInt(s);
When you enter a large number is string which is outside the range of what an int
can accomodate, the overflow happens, and thus all of a sudden you are working on a different number than what was in your string.
当您输入一个超出int
可容纳范围的大量字符串时,就会发生溢出,因此突然之间您正在处理与字符串中不同的数字。
I would suggest you iterate over each character of the string, and then convert each character to integer:
我建议您遍历字符串的每个字符,然后将每个字符转换为整数:
for (char ch: s.toCharArray()) {
// convert ch to integer, and add to the array.
intArray[i] = (int)(ch - '0');
// of course keep incrementing `i`
}
回答by Amit Das
You can simple use Character wrapper class and get the numeric value and add it to array of in.
您可以简单地使用 Character 包装器类并获取数值并将其添加到 in 数组中。
String sample = "12345";
int[] result = new int[sample.length()];
for(int i=0;i<result.length;i++)
{
result[i] = Character.getNumericValue(sample.charAt(i));
}