嘿,我试图从字符串中识别数字并将它们转换为字符串数组,但是使用这段代码我得到的是:
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;
}
}
最佳答案
当你初始化你的字符串数组时:
String[] l = new String[10];
每个索引都包含 null。
当您将一个字符串附加到该空值时,您将字符串“null”附加到您的字符串。
如果你改变:
l[count] += "" + s.charAt(i);
到
if (l[count] == null)
l[count] = "" + s.charAt(i);
else
l[count] += "" + s.charAt(i);
您将摆脱“空”字符串。
我看到您作为答案发布的代码。如果它没有回答问题,则不应将其作为答案发布。您应该将其添加到问题中。
无论如何,您的问题是访问 String 的第 i+2
个字符,这会导致在循环的最后一次迭代中出现 IndexOutOfBoundsException。
不要在同一次迭代中检查第 i
、i+1
和 i+2
字符,您应该检查一个每次迭代中的字符,并使用局部变量来保存当前数字。
您的代码可以比现在简单得多:
public static String[] toArray(String s)
{
ArrayList<String> m = new ArrayList<>();
StringBuilder currentNumber = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
if(Character.isDigit(s.charAt(i))) {
currentNumber.append (s.charAt(i));
} else {
if (currentNumber.length() > 0) {
m.add(currentNumber.toString());
currentNumber.setLength(0);
}
}
}
if (currentNumber.length() > 0) {
m.add(currentNumber.toString());
}
return m.toArray(new String[m.size()]);
}
这会为您使用的输入生成数组 [1, 2, 3, 4, 23, 567, 1]
。
关于java - 我在添加数组的相同索引时得到空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31583683/