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
I'm trying to 3 ints out of a String that is a mix of letters and digits for example avfds:10,5,14 but if character.equals(":") is never showing as true and im not sure why. Thanks for any help
int k is used later in a switch shouldn't be relevant at this point
使用字符时,请尝试使用简单的引号(')而不是双引号(“)
for (String s : "avfds:10,5,14".split(":")[1].split(","))
System.out.println(s);
output:
10
5
14
or:
System.out.println(Arrays.asList("avfds:10,5,14".split(":")[1].split(",")));
output:
[10, 5, 14]
With some 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);
}
}
}
References:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.