日期:2014-05-20  浏览次数:20746 次

如何把字符串"11-13,18,21-25"保存到一个二维数组??
如何把字符串 "11-13,18,21-25 "保存到一个二维数组String   a[][]={ "11 ", "12 ", "13 "},{ "18 "},{ "21 ", "22 ", "23 ", "24 ", "25 "}},其中11-13代表11,12,13;21-25代表21,22,23,24,25;

------解决方案--------------------
用split( ", ")或者 StringTokenizer 先吧数据分隔开 然后再进行其他处理
------解决方案--------------------
public class test{
public static void main(String args[]){
String str = args.length==0? "11-13,18,21-25 ":args[0];
String arr1[][],arr2[] = str.split( ", ");
for(int i=0;i <str2.length;i++){
arr1[i] = arr2[i].split( "- ");
if(arr1[i].length==2){
int tmp1 = Integer.parseInt(arr1[i][0]);
int tmp2 = Integer.parseInt(arr1[i][1]);
arr1[i] = new String[tmp2-tmp1+1];
for(int j=tmp1;j <=tmp2;j++)
arr1[i][j] = " "+j;
}
System.out.println(java.util.Arrays.asList(arr1));
}
}

这个是随手写出的,现在没有JDK所以无法调试,不过估计很接近了
------解决方案--------------------
public static void main(String[] args) {

String str = "11-13,18,21-25 ";
String[][] result = null;
String[] splitResult = str.split( ", ");
result = new String[splitResult.length][];
for (int i = 0; i < splitResult.length; i++) {
String string = splitResult[i];
int index = string.indexOf( '- ');
if(index > = 0){
int start = Integer.parseInt(string.substring(0, index));
int end = Integer.parseInt(string.substring(index+1));
int len = end - start + 1;
result[i] = new String[len];
for (int j = 0; j < len; j++) {
result[i][j] = String.valueOf(start + j);
}
} else {
result[i] = new String[1];
result[i][0] = string;
}
}

// output the result
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
System.out.print( "\t " + result[i][j]);
}
System.out.println();
}
}