2014-12-02 107 views
0

在我的Android应用程序中,我有一个字符串,其值始终为yo_2014_rojo。 我需要将字符串分为三部分:part1 ="yo"part2="2014"part3="rojo"ArrayIndexOutOfBoundsException在拆分字符串

我想如下做到这一点:

String s[] = dato_seleccionado.split("_"); 
String s1 = s[0]; 
String s2 = s[1]; 
String s3 = s[2]; 

但例外的应用程序崩溃:ArrayIndexOutOfBoundsException

任何帮助,欢迎。

+3

你需要把一个断点,似乎'dato_seleccionado'是不是在你的形式期望它崩溃时,否则这将工作得很好。 – 2014-12-02 02:27:25

+0

@Zach如果它为空,OP会得到一个NPE。这绝对不是空的。 – 2014-12-02 02:30:11

+0

@ClaudioRedi,我插入了一个日志来检查dato_seleccionado的值,它现在是12_Diciembre_2014 ...异常说长度= 1,索引= 1 – novato 2014-12-02 02:30:55

回答

2

尝试......

String str = "yo_2014_rojo"; 
StringTokenizer token = new StringTokenizer(str , "_"); 
String part1 = token.nextToken(); //yo 
String part2 = token.nextToken(); //2014 
String part3 = token.nextToken(); //rojo 
1

尝试做这样的:

String[] spliced = dato_seleccionado.split("_"); 

System.out.println(Arrays.toString(spliced)); // check if you have the correct output 

String s1 = spliced[0]; 
String s2 = spliced[1]; 
String s3 = spliced[2]; 
1

stringname.split()需要Perl的正则表达式作为参数。

尝试逃离下划线,就像这样:

String[] spliced = dato_seleccionado.split("\\_");