java中的二维字符串数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19173396/
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
Two dimensional string array in java
提问by Magic
I am new to java please help me with this issue.
I have a string lets say
我是 Java 新手,请帮我解决这个问题。
我有一个字符串可以说
adc|def|efg||hij|lmn|opq
now i split this string and store it in an array using
现在我拆分这个字符串并使用它存储在一个数组中
String output[] = stringname.split("||");
now i again need to split that based on '|' and i need something like
现在我再次需要根据'|'拆分它 我需要类似的东西
arr[1][]=adc,arr[2][]=def
and so on so that i can access each and every element.
something like a 2 dimensional string array.
I heard this could be done using Arraylist, but i am not able to figure it out.
Please help.
arr[1][]=adc,arr[2][]=def
等等,以便我可以访问每个元素。类似于二维字符串数组。我听说这可以使用Arraylist来完成,但我无法弄清楚。请帮忙。
采纳答案by Vimal Bera
Here is your solution except names[0][0]="adc", names[0][1]="def" and so on:
这是您的解决方案,除了 names[0][0]="adc", names[0][1]="def" 等等:
String str = "adc|def|efg||hij|lmn|opq";
String[] obj = str.split("\|\|");
int i=0;
String[][] names = new String[obj.length][];
for(String temp:obj){
names[i++]=temp.split("\|");
}
List<String[]> yourList = Arrays.asList(names);// yourList will be 2D arraylist.
System.out.println(yourList.get(0)[0]); // This will print adc.
System.out.println(yourList.get(0)[1]); // This will print def.
System.out.println(yourList.get(0)[2]); // This will print efg.
// Similarly you can fetch other elements by yourList.get(1)[index]
回答by Sachin Verma
What you can do is:
你可以做的是:
String str[]="adc|def|efg||hij|lmn|opq".split("||");
String str2[]=str[0].split("|");
str2 will be containing abc, def , efg
// arrays have toList() method like:
Arrays.asList(any_array);
回答by wfwei
Can hardly understand your problem...
很难理解你的问题...
I guess you may want to use a 2-dimenison ArrayList : ArrayList<ArrayList<String>>
我猜您可能想使用二维 ArrayList : ArrayList<ArrayList<String>>
String input = "adc|def|efg||hij|lmn|opq";
ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
for(String strs:input.split("||")){
ArrayList<String> strList = new ArrayList<String>();
for(String str:strs.split("|"))
strList.add(str);
res.add(strList);
}