java 如何将字符串拆分为二维数组并根据行访问每个分组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9918474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you split a string into a 2d array and access each grouping based on row?
提问by user1299661
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!
如果有更简单的方法请分享。正如你所知道的,我是一个新手,但我愿意学习。在此示例中,每个单词都由分隔符分隔并自动存储到“file1tags”数组中。如何使用二维数组执行此操作,以便我可以调用具有相同功能的多个数组?提前致谢!
采纳答案by user unknown
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;
}
回答by ControlAltDel
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
}
}
回答by Peter
String example = "a b c \n d e f \n g h i";
String[] rows = example.split("\n");
String[][] table;
for (int i = 0; i < rows.length; i++) {
table[i] = rows[i].split(" ");
}