How can I convert this string to a two dimensional array using java

I have a text file like

    0B85     61
    0B86     6161
    0B86     41
    0B87     69
    0B88     6969
    0B88     49
    0B89     75
    0B8A     7575
    0B8F     6565

      

I want to write this string to a 2D array. (ie) String read[0][0]=0B85

and String read[0][1]=61

. Please suggest any idea to do this with java. Thanks in advance.

+2


a source to share


2 answers


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


a source


Something like (Pseudocode):



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


a source







All Articles