我正在做一项作业,我必须在扫描仪上输入行。
以U8
为例。 U
和 8
都有一个含义,因此,我必须将它们分开。
这是迄今为止我对 U
部分的了解:
userInput = userInput + " ";
index = userInput.indexOf(" ");
strA = userInput.substring(0, index);
userInput = userInput.substring(index+1, userInput.length());
index = userInput.indexOf(" ");
userInput = userInput.substring(index+1, userInput.length());
现在,我只是不知道如何单独提取整数。我怎样才能做到这一点?
最后,我需要从一行中提取多个字符串和整数。所有字符串-整数对均以空格分隔,例如:U8 U7 ...
。
我无法使用Split()
。
最佳答案
离开 Paul 的答案,为了使其能够适用于由空格分隔的任意数量的 char int 输入,您可以使用:
String input = "U80 G9 Q4";
ArrayList<Integer> ints = new ArrayList<Integer>();
ArrayList<Character> chars = new ArrayList<Character>();
for (int i = 0; i < input.length() - 1; i++) {
char letter = input.charAt(i);
String num = "";
for(int j=i+1;j<input.length();j++){
i++;
if(input.charAt(j)!=' '){
num+=input.charAt(j);
}else{
break;
}
}
int number = Integer.parseInt(num + "");
ints.add(number);
chars.add(letter);
}
for (int i = 0; i < ints.size(); i++) {
System.out.println("Letter: " + chars.get(i) + " Number: " + ints.get(i));
}
输出:
Letter: U Number: 80
Letter: G Number: 9
Letter: Q Number: 4
抱歉删除了代码中的提示,但我只需要快速复制/粘贴,因为我必须很快离开,但我希望这会有所帮助!
关于java - Java中如何从字符串中分别提取字符串和整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33585132/