我想知道如何分离一个字符串并将其自动分配给二维数组的特定行,其方式与下面实例化一维数组的方式相同:
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”数组中。我如何使用二维数组执行此操作,以便我可以调用具有相同功能的多个数组?提前致谢!
最佳答案
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;
}
关于java - 如何将字符串拆分为二维数组并根据行访问每个分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9918474/