How can I convert this string to a two dimensional array using java
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 are a split(" ")
long string into parts and then you order the parts into 2 columns String[][] table
.
However, the best solution for this would be to have a class of Entry
some type for each line and have List<Entry>
instead String[][]
.
NOTE. Discarded by formatting, keeping above, but here's what you need
If you have columns.txt
one containing the following:
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 in 2 columns 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 repeat that a is List<Entry>
much better than a String[][]
.
see also
- Effective Java 2nd Edition Item 25: Preferred Lists for Arrays
- Effective Java 2nd Edition Item 50: Avoid Strings Where More Appropriate Types Are
a source to share