求教,JAVA如何将"[a,b,c],[d,e,f,g],[h,i,j],[k,l]"这样的字符串转为数组

2024-12-03 06:45:08
推荐回答(5个)
回答1:

public class AA {
public static void main(String[] args) {
String s="[a,b,c],[d,e,f,g],[h,i,j],[k,l]";
String s1=s.replaceAll("],", "]-");
String[] str=s1.split("-");
for(int i=0;i System.out.println(str[i]);
}
}
}

正则不会,这样写可以吗?

回答2:

正则方法,据说效率不高
String str = "[a,b,c],[d,e,f,g],[h,i,j],[k,l]";
Pattern p = Pattern.compile("\\[([a-z],?)+\\]");
Matcher m = p.matcher(str);
String[] strs = new String[0];
while(m.find()){
String s1 = m.group();
strs = Arrays.copyOf(strs, strs.length + 1);
strs[strs.length -1] = s1;
}

回答3:

String str = "[a,b,c],[d,e,f,g],[h,i,j],[k,l]";
String arr[] = str.split("\\]+,");
for(int i=0;i arr[i]=arr[i]+"]";
}
for(String s:arr){
System.out.println(s);
}

回答4:

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
StringTool tool = new StringTool();
String str = "[a,b,c],[d,e,f,g],[h,i,j],[k,l]";
String[] list = tool.fun(str);
for(String e : list)
{
System.out.println(e);

}
}

}

class StringTool {
public StringTool(){}

public String[] fun(String str)
{
String[] r = str.split("\\],\\[");
int length = r.length;
String[] result = new String[length];
for(int i = 0; i < length; i++)
{
result[i] = "[" + r[i].replaceAll("\\[", "").replaceAll("\\]", "") + "]";
}

return result;
}
}

回答5:

public static void main(String[] args) {
String str = "[a,b,c],[d,e,f,g],[h,i,j],[k,l]";
String regex = "[???]";
String[] arr = str.split(regex);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
}