我有一个用逗号分隔的正整数的字符串,例如:

1,34,433,12


确定字符串是否至少包含1个整数的最快方法是什么?

现在,我split(","),遍历结果String[],并尝试将每个元素解析为一个int。

这是为了获取字符串的List<Integer>,但是我想要最快的方法来确定字符串是否对此有效。

1a,2b,13是可以接受的。 1a,2b,13c是不可接受的。

最佳答案

尝试:

public static boolean containsInt(String string) {
    boolean onlyDigits = true;
    boolean atLeastOneDigit = false;
    int len = string.length();
    for (int i = 0; i < len; i++) {
        char c = string.charAt(i);
        if (c == ',') {
            if (atLeastOneDigit && onlyDigits) {
                return true;
            }
            onlyDigits = true;
            atLeastOneDigit = false;
            continue;
        }
        boolean isDigit = c >= '0' && c <= '9';
        onlyDigits &= isDigit;
        atLeastOneDigit |= isDigit;
    }
    return atLeastOneDigit && onlyDigits;
}


现在,使用番石榴更具可读性的版本:

public static boolean containsInt(String text) {
    for (String s : Splitter.on(',').split(text) {
        if (Ints.tryParse(s) != null)
            return true;
    }
    return false;
}

07-24 09:50
查看更多