[英]how to convert this string into two dimensional array using java
I have text file as 我有文本文件
0B85 61
0B86 6161
0B86 41
0B87 69
0B88 6969
0B88 49
0B89 75
0B8A 7575
0B8F 6565
I want to write this string into two dimensional array. 我想将此字符串写入二维数组。 (ie)
String read[0][0]=0B85
and String read[0][1]=61
. (即)
String read[0][0]=0B85
和String read[0][1]=61
。 Please suggest any idea to do this using java. 请提出使用Java的任何想法。 Thanks in advance.
提前致谢。
Something like this works: 像这样的作品:
String s = "0B85 61 0B86 6161 0B86 41 0B87 69 0B88"
+ " 6969 0B88 49 0B89 75 0B8A 7575 0B8F 6565";
String[] parts = s.split(" ");
String[][] table = new String[parts.length / 2][2];
for (int i = 0, r = 0; r < table.length; r++) {
table[r][0] = parts[i++];
table[r][1] = parts[i++];
}
System.out.println(java.util.Arrays.deepToString(table));
// prints "[[0B85, 61], [0B86, 6161], [0B86, 41], [0B87, 69],
// [0B88, 6969], [0B88, 49], [0B89, 75], [0B8A, 7575], [0B8F, 6565]]
Essentially you split(" ")
the long string into parts, then arrange the parts into a 2 column String[][] table
. 本质上,您是
split(" ")
长字符串split(" ")
成多个部分,然后将这些部分排列成2列的String[][] table
。
That said, the best solution for this would be to have a Entry
class of some sort for each row, and have a List<Entry>
instead of a String[][]
. 就是说,对此的最佳解决方案是为每行具有某种
Entry
类,并具有List<Entry>
而不是String[][]
。
NOTE: Was thrown off by formatting, keeping above, but following is what is needed
注意:通过格式化,保留上面,但下面是需要
If you have columns.txt
containing the following: 如果您的
columns.txt
包含以下内容:
0B85 61
0B86 6161
0B86 41
0B87 69
0B88 6969
0B88 49
0B89 75
0B8A 7575
0B8F 6565
Then you can use the following to arrange them into 2 columns String[][]
: 然后,您可以使用以下内容将它们分成2列
String[][]
:
import java.util.*;
import java.io.*;
//...
List<String[]> entries = new ArrayList<String[]>();
Scanner sc = new Scanner(new File("columns.txt"));
while (sc.hasNext()) {
entries.add(new String[] { sc.next(), sc.next() });
}
String[][] table = entries.toArray(new String[0][]);
System.out.println(java.util.Arrays.deepToString(table));
I will reiterate that a List<Entry>
is much better than a String[][]
, though. 我将重申
List<Entry>
比String[][]
好得多。
Something like (Pseudo code): 类似于(伪代码)的东西:
parts = yourData.split()
out = new String[ parts.length/2 ][2];
int j=0;
for i=0, i < parts.length -1, i+2:
out[j][0] = parts[i]
out[j][1] = parts[i+1]
j++
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.