如何将字符串拆分为2d数组并根据行访问每个分组? [英] How do you split a string into a 2d array and access each grouping based on row?

查看:103
本文介绍了如何将字符串拆分为2d数组并根据行访问每个分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何分离字符串并将其自动分配给2d数组的特定行,其方式与在以下实例化一维数组的方式相同:

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

如果有任何更简单的方法,请分享.如您所知,我是一个新手,但我愿意学习.在此示例中,每个单词都由定界符分隔,并自动存储到"file1tags"数组中.如何使用2d数组执行此操作,以便可以调用具有相同功能的多个数组?预先感谢!

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!

推荐答案

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", " "));
}

新手友好:

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

这篇关于如何将字符串拆分为2d数组并根据行访问每个分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆