【发布时间】:2015-07-23 09:43:31
【问题描述】:
嘿,我试图从字符串中识别数字并将它们转换为字符串数组,但是使用这段代码我得到的是:
IE: [null1, null2, exc..]
我不知道如何取出这个空值。
我也想找到一种方法来做到这一点,没有数组,因为我应该手动增加它的长度。
有什么建议吗?谢谢!
public class ProvaToArray {
public static void main(String[] x) {
String s = "1-2-3-4-lorem23ip567um1";
String[] ris = toArray(s);
System.out.println(Arrays.toString(ris)); //should printout [1, 2, 3, 4, 23, 567, 1]
}
public static String[] toArray(String s){
String[] l = new String[10];
int count = 0;
for(int i = 0; i < s.length() - 1; i++){
if(estNumber(s.charAt(i) + "")){
l[count] += "" + s.charAt(i);
if(!estNumber(s.charAt(i+1) + "")){
count++;
}
}
if(i+1 == s.length()-1){
if(estNumber(s.charAt(i+1) + "")){
l[count] = "" + s.charAt(i+1);
}
}
}
return l;
}
public static boolean estNumber(String i){
if(i.matches("^-?\\d+$"))
return true;
else
return false;
}
}
【问题讨论】: