Split string into matrix array - java

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?

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

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

Related

How to covert comma separated string to a 2D array in Java?

For example I have some comma separated strings
"aron, IA52, 20"
"john, IA61, 23"
"kleo, IA32, 42"
How can I convert them to a 2 dimensional array in the easiest way possible?
As already pointed out in comments, you should use split() while iterating over your comma separated string list and populate your array accordingly. Here is sample code to give you some idea:
List<String> input = Arrays.asList("aron, IA52, 20", "john, IA61, 23", "kleo, IA32, 42");
String[][] array = new String[3][3];
int row = 0;
// Loop Over Comma Separated List and split each string to populate 2D array
for (String commaSeparatedStr : input) {
String[] parts = commaSeparatedStr.split(",");
System.arraycopy(parts, 0, array[row], 0, parts.length);
row++;
}
// Print array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(array[i][j]);
System.out.println();
}
This prints:
aron IA52 20
john IA61 23
kleo IA32 42
The provided function will parse the string to the 2D matrix.
Below is the format of the string that you need to provide to this function.
1.2,2.3,3.5\n3.1,4.70,5.0
function
public double[][] parseStingToArray(String str) {
System.out.println(str);
String arr1[] = str.split("\n");
double[][] ans = new double[arr1.length][];
for (int i = 0; i < arr1.length; i++) {
String[] col = arr1[i].split(",");
ans[i] = new double[col.length];
for (int j = 0; j < col.length; j++) {
ans[i][j] = Double.parseDouble(col[j]);
}
}
doubleArray = ans;
return ans;
}

String to int array [][] - JAVA

I have a board game define as
boardArray = new int[4][4];
and I have a string in this format:
String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]"
Is there a way to put it in the int array? Consider that it should look like this
[0,0,2,0]
[0,0,2,0]
[0,0,0,0]
[0,0,0,0]
You could simply do the following:
String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]";
String myNums[] = s.split("[^0-9]+");
//Split at every non-digit
int my_array[][] = new int[4][4];
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
my_array[i][j] = Integer.parseInt(myNums[i*4 + j + 1]);
//The 1 accounts for the extra "" at the beginning.
}
}
//Prints the result
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++)
System.out.print(my_array[i][j]);
System.out.println();
}
If you want to to it dynamically, I've written a librray: https://github.com/timaschew/MDAAJ
The nice thing is, that it's really fast, because internally it's a one dimensional array, but provides you same access and much more nice features, checkout the wiki and and tests
MDDA<Integer> array = new MDDA<Integer>(4,4);
or initialize with an existing array, which is one dimensional "template", but will be converted into your dimensions:
Integer[] template = new Integer[] {0,0,2,0, 0,0,2,0, 0,0,0,0, 0,0,0,0};
MDDA<Integer> array = new MDDA<Integer>(template, false, 4,4);
//instead of array[1][2];
array.get(1,2); // 2

Java: Storing values in 2D Array

I have a problem with storing values in a multidimensional array. The main concept of the idea is that I have an arraylist which is called user_decide and I transform it in a array. So, the decide array looks like [1, 45, 656, 8, 97, 897], but all the rows don't have the same number of elements. Then, I split this replace [,] and spaces and I would like to store each value individually in a 2D array. So, I split it with the "," and try to store each value in a different position. Everything seems to be printed great, even the cut[j] is what I want to store, but I get a java.lang.NullPointerException, which I don't get. The count variable is actually the count = user_decide.size()
String [] decide = user_decide.toArray(new String[user_decide.size()]);
for (int i = 0; i < count; i ++){
decide[i] =
decide[i].replaceAll("\\s", "").replaceAll("\\[","").replaceAll("\\]", "");
}
String [][] data1 = new String[count][];
for (int i = 0; i < count; i++){
String [] cut = decide[i].split("\\,");
for (int j = 0; j < cut.length; j++){
System.out.println(cut[j]);
data1[i][j] = cut[j];
}
}
Another question is why I cannot store it in a Int [][] array? Is there a way to do that?
Thank you a lot.
** EDIT **
I just made an edit about my answer after I accepted the question. I am trying to store it in a 2D int array.
String [][] data1 = new String[user_decide.size()][];
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
data1[i] = decide[i].split("\\,");
for (int j = 0; j < data1[i].length; j++) {
data[i] = new int [data1[i].length];
data[i][j] = Integer.parseInt(data1[i][j]);
System.out.println(data1[i][j]);
}
}
Ivaylo Strandjev's answer shows the reason for your problem. But there's a much simpler solution:
String [][] data1 = new String[count][];
for (int i = 0; i < count; i++){
data1[i] = decide[i].split("\\,");
System.out.println(Arrays.toString(data1[i]));
}
Also, you don't need to escape the comma.
EDIT
Saw your edit. There is a big mistake, see my comment in your code:
String [][] data1 = new String[user_decide.size()][];
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
data1[i] = decide[i].split("\\,");
for (int j = 0; j < data1[i].length; j++) {
data[i] = new int [data1[i].length]; // This line has to be prior to the
// inner loop, or else you'll overwrite everything but the last number.
data[i][j] = Integer.parseInt(data1[i][j]);
System.out.println(data1[i][j]);
}
}
If all you want is the int[], this is what I would do:
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
String[] temp = decide[i].split(",");
data[i] = new int [temp.length];
for (int j = 0; j < temp.length; j++){
data[i][j] = Integer.parseInt(temp[j]);
System.out.println(data1[i][j]);
}
}
There are probably nicer ways, but I don't know why you are using user_decide.size() ( a Collection) for the condition and decide[i] (an array) within the loop. There's no good reason I can think of mixing this, as it could lead to errors.
In java you will need to also allocate data[i], before copying contents:
for (int i = 0; i < count; i++){
data1[i] = new String[cut.length];
String [] cut = decide[i].split("\\,");
for (int j = 0; j < cut.length; j++){
System.out.println(cut[j]);
data1[i][j] = cut[j];
}
}
Before copying contents:

Convert String into 2D int array

I have problem with conversion from String into two dimension int array.
Let's say I have:
String x = "1,2,3;4,5,6;7,8,9"
(In my program it will be String from text area.) and I want to create array n x n
int[3][3] y = {{1,2,3},{4,5,6},{7,8,9}}
(Necessary for next stages.) I try to split the string and create 1 dimensional array, but I don't have any good idea what to do next.
As you suggest I try split at first using ; then , but my solution isn’t great. It works only when there will be 3 x 3 table. How to create a loop making String arrays?
public int[][] RunMSTFromTextFile(JTextArea ta)
{
String p = ta.getText();
String[] tp = p.split(";");
String tpA[] = tp[0].split(",");
String tpB[] = tp[1].split(",");
String tpC[] = tp[2].split(",");
String tpD[][] = {tpA, tpB, tpC};
int matrix[][] = new int[tpD.length][tpD.length];
for(int i=0;i<tpD.length;i++)
{
for(int j=0;j<tpD.length;j++)
{
matrix[i][j] = Integer.parseInt(tpD[i][j]);
}
}
return matrix;
}
After using split, take a look at Integer.parseInt() to get the numbers out.
String lines[] = input.split(";");
int width = lines.length;
String cells[] = lines[0].split(",");
int height = cells.length;
int output[][] = new int[width][height];
for (int i=0; i<width; i++) {
String cells[] = lines[i].split(",");
for(int j=0; j<height; j++) {
output[i][j] = Integer.parseInt(cells[j]);
}
}
Then you need to decide what to do with NumberFormatExceptions
Split by ; to get rows.
Loop them, incrementing a counter (e.g. x)
Split by , to get values of each row.
Loop those values, incrementing a counter (e.g. y)
Parse each value (e.g. using one of the parseInt methods of Integer) and add it to the x,y of the array.
If you have already created an int[9] and want to split it into int[3][3]:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
toArray[i][j] = fromArray[(3*i) + j);
}
}
Now, if the 2-dimensional array is not rectangular, i.e. the size of inner array is not same for all outer arrays, then you need more work. You would do best to use a Scanner and switch between nextString and next. The biggest challenge will be that you will not know the number of elements (columns) in each row until you reach the row-terminating semi-colon
A solution using 2 splits:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
String[][] result = new String[x.length][];
for (int i = 0; i<x.length; i++) {
result[i] = x[i].split(",");
}
This give a 2 dimension array of strings you will need to parse those ints afterwards, it depends on the use you want for those numbers. The following solution shows how to parse them as you build the result:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
int[][] result = new int[x.length][];
for (int i = 0; i < x.length; i++) {
String[] row = x[i].split(",");
result[i] = new int[row.length];
for(int j=0; j < row.length; j++) {
result[i][j] = Integer.parseInt(row[j]);
}
}
Super simple method!!!
package ADVANCED;
import java.util.Arrays;
import java.util.Scanner;
public class p9 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String x=sc.nextLine();
String[] array = x.split(",");
int length_x=array.length;
int[][] two=new int[length_x/2][2];
for (int i = 0; i <= length_x-1; i=i+2) {
two[i/2][0] = Integer.parseInt(array[i]);
}
for (int i = 1; i <= length_x-1; i=i+2) {
two[i/2][1] = Integer.parseInt(array[i]);
}
}
}

Converting a 2d array of ints to char and string in Java

How can I convert the ints in a 2d array into chars, and strings? (seperately)
If I copy ints to a char array i just get the ASCII code.
For example:
public int a[5][5]
//some code
public String b[5][5] = public int a[5][5]
Thanks
This question is not very well-phrased at all. I THINK what you're asking is how to convert a two-level array of type int[][] to one of type String[][].
Quite frankly, the easiest approach would simply leave your array as-is... and convert int values to String's when you use them:
Integer.toString(a[5][5]);
Alternatively, you could start with a String[][] array in the first place, and simply convert your int values to String when adding them:
a[5][5] = new String(myInt);
If you really do need to convert an array of type int[][] to one of type String[][], you would have to do so manually with a two-layer for() loop:
String[][] converted = new String[a.length][];
for(int index = 0; index < a.length; index++) {
converted[index] = new String[a[index].length];
for(int subIndex = 0; subIndex < a[index].length; subIndex++){
converted[index][subIndex] = Integer.toString(a[index][subIndex]);
}
}
All three of these approaches would work equally well for conversion to type char rather than String.
Your code must basically go through your array and transform each int value into a String. You can do this with the String.toString(int) method.
You can try that :
String[][] stringArray = new String[a.length][];
for(int i = 0; i < a.length; i++){
stringArray[i] = new String[a[i].lenght];
for(int j = 0; j < a[i].length; j++){
stringArray[i][j] = Integer.toString(a[i][j]);
}
}
If you want the int number as a string then you can use the Integer.toString() function.
b[1][1] = Integer.toString(a[1][1]);
String [][]b = new String[a.length][];
for(int i=0; i<a.length; i++) {
int [] row = a[i];
b[i] = new String[row.length];
for(int j=0; j<row.length; j++) {
b[i][j] = Integer.toString(row[j]);
}
}
To convert a 2D array into String you can use Arrays.deepToString(stringArr).

Categories

Resources