java 将字符串数组转换为 int 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15281894/
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
converting string array into int array
提问by user1721540
this is what i have so far, i need to convert this string array into just an array of integers, the string array looks something like this
这是我到目前为止所拥有的,我需要将此字符串数组转换为一个整数数组,字符串数组看起来像这样
wholef[0] = "2 3 4";
wholef[1] = "1 3 4";
wholef[2] = "5 3 5";
wholef[3] = "4 5 6";
wholef[4] = "3 10 2";
these values come from a text file that i read from but now i need to convert this into one big array of integers, im trying to use the split method but im not sure if it will work on this kind of setup. if anyone can give me a better way it would be nice but i just need to convert this into an array of integers, thats really all i need.
这些值来自我读取的文本文件,但现在我需要将其转换为一个大的整数数组,我尝试使用 split 方法,但我不确定它是否适用于这种设置。如果有人能给我一个更好的方法,那就太好了,但我只需要将它转换为一个整数数组,这就是我所需要的。
for(int k = 0; k < fline; k++)
{
String[] items = wholef[k].replaceAll(" ", "").split(",");
int[] parsed = new int[wholef[k].length];
for (int i = 0; i < wholef[k].length; i++)
{
try
{
parsed[i] = Integer.parseInt(wholef[i]);
} catch (NumberFormatException nfe) {};
}
}
This is the new code im using now, its very close cause i only get one error
这是我现在使用的新代码,它非常接近,因为我只收到一个错误
int q = 0;
for (String crtLine : wholef)
{
int[] parsed = new int[wholef.length];
String[] items = crtLine.split(" ");
for (String crtItem: items)
{
parsed[q++] = Integer.parse(crtItem);
}
}
the error is this java:97: error: cannot find symbol parsed[q++} = Integer.parse(crtItem); ^ symbol: method parse(String) location: class Integer 1 error
错误是这个 java:97: error: cannot find symbol parsed[q++} = Integer.parse(crtItem); ^ 符号:方法解析(字符串)位置:类整数 1 错误
回答by niculare
Try this:
试试这个:
int i = 0;
for (String crtLine : wholef) {
String[] items = crtLine.split(" ");
for (String crtItem: items) {
parsed[i++] = Integer.parseInt(crtItem);
}
}
回答by Apollo SOFTWARE
This take your string array and dumps it into intwholef[n..total]; If you want it into a 2D array or an object array you have to do some additional. Then you can do an array of objects, and have each set of values as an attribute.
这将获取您的字符串数组并将其转储到 intwholef[n..total]; 如果你想把它变成一个二维数组或一个对象数组,你必须做一些额外的事情。然后你可以做一个对象数组,并将每组值作为一个属性。
String[] parts = wholef[0].split(" ");
int[] intwholef= new int[parts.length];
for(int n = 0; n < parts.length; n++) {
intwholef[n] = Integer.parseInt(parts[n]);
}