How do you split a string into a 2d array and access each grouping based on row?

17,419

Solution 1

public static String [][] to2dim (String source, String outerdelim, String innerdelim) {

    String [][] result = new String [source.replaceAll ("[^" + outerdelim + "]", "").length () + 1][]; 
    int count = 0;
    for (String line : source.split ("[" + outerdelim + "]"))
    {
        result [count++] = line.split (innerdelim);
    }
    return result;
}

public static void show (String [][] arr)
{
    for (String [] ar : arr) {
        for (String a: ar) 
            System.out.print (" " + a);
        System.out.println ();
    }
}   

public static void main (String args[])
{
    show (to2dim ("a b c \n d e f \n g h i", "\n", " "));
}

newbie friendly:

public static String [][] to2dim (String source, String outerdelim, String innerdelim) {
    // outerdelim may be a group of characters
    String [] sOuter = source.split ("[" + outerdelim + "]"); 
    int size = sOuter.length;
    // one dimension of the array has to be known on declaration:
    String [][] result = new String [size][]; 
    int count = 0;
    for (String line : sOuter)
    {
        result [count] = line.split (innerdelim);
        ++count;
    }
    return result;
}

Solution 2

here's a simple example


String example = "a b c \n d e f \n g h i";
String[] rows = example.split("\n");
for (int i = 0; i < rows.length; i++) {
  String[] columns = rows[i].split(" ");
  for (int j = 0; j < columns.length; j++) {
    //do something
  }
} 
Share:
17,419
user1299661
Author by

user1299661

Updated on June 26, 2022

Comments

  • user1299661
    user1299661 almost 2 years

    I would like to know how I can separate a string and assign it to a specific row of a 2d array automatically in the same fashion that the single dimensional array is instantiated below:

    public class TestArray {
      public static void main (String [] args) {
    
        String file1description= "We went to the mall yesterday.";
        String[] file1tags;
        String delimiter= " ";
        file1tags = file1description.split (delimiter);
        for (int i = 0; i < file1tags.length; i++) {
          System.out.println (file1tags[i]);
        }
      }
    }
    

    If there are any simpler ways please share. As you can tell I am quite a novice, but I am willing to learn. In this example, each word is separated by the delimiter and stored automatically into the "file1tags" array. How can I do this with a 2d array, so that I can call multiple arrays that have this same function? Thanks in advance!