[英]Convert string to multidimensional int array
I'm having slight trouble converting a string which I am reading from a file into a multidimensional int array having found what I believe are suggestions here . 我在将我从文件中读取的字符串转换为多维int数组时遇到了一些麻烦, 在这里我发现了建议。
See this file here for string content. 有关字符串内容,请参见此处 。
Essentially I would like to replace the CR and LF so as to create a multi dimensional int array. 本质上,我想替换CR和LF,以创建多维int数组。
As per my code below where could I be going wrong? 根据我下面的代码,我可能在哪里出错?
public static void fileRead(String fileContent) {
String[] items = fileContent.replaceAll("\\r", " ").replaceAll("\\n", " ").split(" ");
int[] results = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
results[i] = Integer.parseInt(items[i]);
System.out.println(results[i]);
} catch (NumberFormatException nfe) {};
}
}
EDIT: I'm not encountering any errors. 编辑:我没有遇到任何错误。 The above logic only creates an int array of size two ie results[0] = 5 and results[ 1] = 5
上面的逻辑仅创建一个大小为2的int数组,即result [0] = 5和results [1] = 5
Thanks for any suggestions. 感谢您的任何建议。
Here's Java 8 solution: 这是Java 8解决方案:
private static final Pattern WHITESPACE = Pattern.compile("\\s+");
public static int[][] convert(BufferedReader reader) {
return reader.lines()
.map(line -> WHITESPACE.splitAsStream(line)
.mapToInt(Integer::parseInt).toArray())
.toArray(int[][]::new);
}
Usage (of course you can read from file as well): 用法(当然您也可以从文件中读取):
int[][] array = convert(new BufferedReader(new StringReader("1 2 3\n4 5 6\n7 8 9")));
System.out.println(Arrays.deepToString(array)); // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.