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?

2 Answers 2

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(..)

Sign up to request clarification or add additional context in comments.

Comments

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]);
    }
}

3 Comments

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."
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.
Replaced StringTokenizer with String.split() as suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.