开发者

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. (i.e) String read[0][0]=0B85 and String read[0][1]=61. Please suggest any idea to do this using 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.

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[][].


NOTE: Was thrown off by formatting, keeping above, but following is what is needed

If you have columns.txt 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 into 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 will reiterate that a List<Entry> is much better than a String[][], though.

See also

  • Effective Java 2nd Edition, Item 25: Prefer lists to arrays
  • Effective Java 2nd Edition, Item 50: Avoid strings where other types are more appropriate


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++
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜