1

I have a String:

1,3,4,5,
1,4,5,0,
2,5,3,8,

That I want to store in a variable matrix (int[][]). What is the best way to accomplish this? Should I use the String class' methods? Or should I use a Regex?

Mohit Deshpande
  • 53,877
  • 76
  • 193
  • 251

2 Answers2

6

First (by String.split(..)) split on newline, then split the items of each of the resultant array on ,. Then parse each using Integer.parseInt(..)

Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
2
String input = "1,3,4,5,\n1,4,5,0,\n2,5,3,8,";

String[] str1 = input.split("\n");
int[][] matrix = new int[str1.length][];
for (int i = 0; i < matrix.length; i++) {
    String[] str2 = str1[i].split(",");
    matrix[i] = new int[str2.length];
    for (int j = 0; j < matrix[i].length; j++) {
        matrix[i][j] = Integer.parseInt(str2[j]);
    }
}
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
  • 2
    `StringTokenizer` is de-facto deprecated: "It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead." – Bozho Mar 20 '11 at 00:02
  • Hmm that's interesting that the JavaDoc actually recommends that now, didn't realize that. It seems like it's best to avoid regex where possible though. As well StringTokenizer is 3 times faster in this case (10k iterations) and does less object creation, although likely doesn't matter. – WhiteFang34 Mar 20 '11 at 00:13
  • Replaced `StringTokenizer` with `String.split()` as suggested. – WhiteFang34 Mar 20 '11 at 09:56