1

I am trying to convert an Array of Strings into another 2D Array of Strings by using .split(), so that every row of the 2D Array is filled with one of the split parts. The Array i want to split, should be split into 3 parts as followed:

Content of the Array:

[0]= "25-Mar-18", [1]= "20-Dec-18",[2]= "1-Jan-15";

How it should look like in the 2D Array:

row [0] [0]= "25", [1]= "Mar", [2]= "18";
row [1] [0]= "20", [1]= "Dec", [2]= "18";
row [2] [0]= "1",  [1]= "Jan", [2]= "15";

You get the point... Here is my Code. And my Question: is it even possible to store the array with.split into a 2D Array?

Code:

String[] string = {"25-Mar-18", "20-Dec-18", "1-Jan-15"};
String[] [] parts;

void draw(){
  for(int i=0; i<string.length;i++){
    for(int j=0; j<3;j++){
      parts[i] [j] = string[i].split("-");
    }
  }
  printArray(parts);
}

Error:

Error: Type mismatch, "java.lang.String[]" does not match with "java.lang.String"

4 Answers 4

1

You have to use :

parts[i] = string[i].split("-");

Instead of :

parts[i][j] = string[i].split("-");

Why!

because string[i].split("-") return an array and not a single String, and the parts if an array of array.


Now it gives me a NullPointerException...

because you are not Initialize the array String[] [] parts; to solve your problem you can use :

parts = new String[string.length][];
Sign up to request clarification or add additional context in comments.

1 Comment

@OliverTworkowski because you are not Initialize the array check my edit!
1

String.split("-") method returns an array of Strings. Ex: if "25-Nar-18" then {["25"], ["Mar"], ["18"]}

So your code should be corrected as

for(int i=0; i<string.length;i++){
    String[] temp = string[i].split("-");
    for(int j=0; j<3;j++){
      parts[i] [j] = temp[j];
    }
}

1 Comment

Hey, this also gives me a nullpointerexception in the line of the 2D array
0

You are getting a nullPointerException because you aren't initialising the array. Do

  String[] string = {"25-Mar-18", "20-Dec-18", "1-Jan-15"};
  String[][] parts = new String[3][3];

  void draw() {
    for(int i = 0; i < string.length; i++){
      parts[i] = string[i].split("-");
    }
  }

Comments

0
String[] string = {"25-Mar-18", "20-Dec-18", "1-Jan-15"};
String[] [] parts=new String[string.length][];

void setup(){
  for(int i=0; i<string.length;i++){
    parts[i]=string[i].split("-");
  }
  printArray(parts[0]);
}

Question anwsered by 'YCF_L'

Comments

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.