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

求教:怎么分割这个字符串呀 ???
String   ttt=   "2004,1,2005,0,2006,3,2004,0,2005,0,2006,1, ";
分割为
aaa[0]=   "2004,1,2005,0,2006,3, ";

aaa[1]=   "2004,0,2005,0,2006,1, ";


------解决方案--------------------
String t = ttt.substring(0,ttt.length()/2);
String tt = ttt.substring(ttt.length()/2,ttt.length());
------解决方案--------------------
LZ 为社么不把用|分割呢?
String ttt= "2004,1,2005,0,2006,3|2004,0,2005,0,2006,1, ";
Scanner scanner=new Scanner( "\\| ");
取值,毕竟没有规律的字串是很难分割的
------解决方案--------------------
正则表达式
------解决方案--------------------
二楼的好像不正确吧~!

String ttt= "2004,1,2005,0,2006,33,2004,0,2005,0,2006,1, ";
String tt = ttt.substring(0, ttt.length()/2+1);
String t = ttt.substring(ttt.length()/2+1, ttt.length());
------解决方案--------------------
String s = "2004,1,2005,0,2006,3,2004,0,2005,0,2006,1, ";
Pattern p = Pattern.compile( "([0-9]{4},[0-9]{1},[0-9]{4},[0-9]{1},[0-9]{4},) ");
Matcher m = p.matcher(s);
while(m.find()){
System.out.println(m.group());
}
------解决方案--------------------
import java.util.regex.*;


public class Test1
{
public static void main(String[] args)
{
String s = "2004,1,2005,0,2006,3,2004,0,2005,0,2006,1, ";
s=s.replaceAll( "3, ", "3. ");
String[] strs=s.split( "\\. ");
System.out.println(strs[0]+ ", ");
System.out.println(strs[1]);
}

}
------解决方案--------------------
正则当然是第一选择了。
Pattern p = Pattern.compile( "(\\d{4},\\d{1,},\\d{4},\\d{1,},\\d{4},\\d{1,}) ");
Matcher m = p.matcher(s);
while(m.find())
{
System.out.println(m.group());
}
如果不熟悉,也可以用土方法。比如split成数组,然后6拼1
String arr[] = s.split( ", ");

for(int i=0;i <arr.length/6;i++)
{
String combit = arr[6*i]+ ', '+arr[6*i+1]+ ', '+arr[6*i+2]+ ', '+arr[6*i+3]+ ', '+arr[6*i+4]+ ', '+arr[6*i+5];
System.out.println(combit);
}
或者干脆用indexOf找6次

int index = 0;
int temp = 0;
while(true)
{

for(int i=0;i <6;i++){
temp = s.indexOf( ', ',temp+1);
if(temp <0)
break;
}
if(temp <0)
break;
String sub = s.substring(index,temp);
index = temp+1;

System.out.println(sub);
}

------解决方案--------------------
取字符串简单,设计得不好,应该在中间放一字符,比较直观