protected void intFinder(int k, String inputLine) {
int legnth = inputLine.length();
Integer extractedNumber = null;
for (int i = 0; i < legnth; i++) {
Character character = inputLine.charAt(i);
if (character.equals(":")) {
i++;
extractedNumber += character;
character = inputLine.charAt(i);
} else if (character.equals(",")) {
i++;
character = inputLine.charAt(i);
while (Character.isDigit(character)) {
extractedNumber += character;
i++;
character = inputLine.charAt(i);
}
//code ommited
我正在尝试使用字母和数字混合的字符串中的3个整数,例如avfds:10,5,14但是如果character.equals(“:”)永远不会显示为真且我不确定为什么。谢谢你的帮助
后来在开关中使用的int k在这一点上应该不相关
答案 0 :(得分:0)
使用字符时,请尝试使用简单的引号(')而不是double(“)
答案 1 :(得分:0)
for (String s : "avfds:10,5,14".split(":")[1].split(","))
System.out.println(s);
输出:
10
5
14
或:
System.out.println(Arrays.asList("avfds:10,5,14".split(":")[1].split(",")));
输出:
[10, 5, 14]
答案 2 :(得分:0)
有些guava:
package com.stackoverflow.so20477116;
import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import java.util.List;
public class Extract {
private static final Splitter SPLITTER = Splitter.on(CharMatcher.JAVA_DIGIT.negate()).omitEmptyStrings();
public static void main(final String[] args)
{
final List<Integer> result = Lists.newArrayList(Iterables.transform(SPLITTER.split("avfds:10,5,14"), ToInt.INSTANCE));
System.out.println(result); // [10, 5, 14]
}
// String => Integer
private static enum ToInt implements Function<String, Integer> {
INSTANCE;
@Override
public Integer apply(final String input)
{
return input == null ? null : Ints.tryParse(input);
}
}
}
<强>参考文献:强>