gpt4 book ai didi

java - 多行字符串到数组

转载 作者:行者123 更新时间:2023-12-01 22:18:08 24 4
gpt4 key购买 nike

我有一个多行字符串:

40 40 40 
100 100 100
200 200 200
100 50 200 100
150 150 150
50 60 70 80 90

我需要它作为二维数组。我试图通过 split、 Guava Splitter 和其他一些技术来做到这一点,但它仍然不起作用。

public void readTextFile() throws IOException {
content = new String(Files.readAllBytes(Paths.get("/home/cosaquee/dane.txt")));

Splitter niceCommaSplitter = Splitter.on('\n').omitEmptyStrings().trimResults();

Iterable<String> tokens2 = niceCommaSplitter.split(content);

for(String token: tokens2){
boolean atleastOneAlpha = token.matches(".*[a-zA-Z]+.*");
if (!atleastOneAlpha) {
arrayList.add(token);
System.out.println(token);
}
}
}

这就是我现在的代码。我的每一行都有数组列表,但我不知道如何将其变成二维数组。我尝试了旧的 for ,但不知道如何迭代每个字符串并将它们拆分并保存到数组。

最佳答案

为什么要使用分离器?字符串带有 split() 方法。另外,只需使用双 for 循环来填充二维数组。

public String[][] readTextFile() throws IOException {
String content = new String(Files.readAllBytes(Paths.get("yourpath.txt")));

// get the lines
String[] lines = content.split("\\r?\\n"); // split on new lines

// get the max amt of nums in the file in a single line
int maxInLine = 0;
for (String x : lines) {
String[] temp = x.split("\\s+"); // split on whitespace
if (temp.length > maxInLine) {
maxInLine = temp.length;
}
}

String[][] finalArray = new String[lines.length][maxInLine]; // declare and instantiate the array of arrays

// standard double for loop to fill up your 2D array
for (int i = 0; i < lines.length; i++) {
String[] temp = lines[i].split("\\s+"); // split on whitespace
for (int j = 0; j < temp.length; j++) {
finalArray[i][j] = temp[j];
}
}
return finalArray;
}

关于java - 多行字符串到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30581614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com