4
\$\begingroup\$

What would be the best way to get the first two numbers of a string?

I can do it like this:

public static String getFirstTwoNumbersOfString(String s){
        if(s == null)
            return "";

        String numbers = "0123456789";

        String result = "";

        for(int i=0; i<s.length() && result.length()<2; i++){
            String c = String.valueOf(s.charAt(i));
            if(numbers.contains(c)){
                result += c;
            }
        }

        return result;
    }

But I think there must be a better way, more concise and with better performance.

\$\endgroup\$
2
\$\begingroup\$

In fact, you can:

public static String getFirstTwoNumbersOfString2(String s) {
    StringBuilder sb = new StringBuilder(2); // Capacity of 2 chars.

    for (char c : s.toCharArray()) {
        if (Character.isDigit(c)) {
            sb.append(c);

            if (sb.length() == 2) {
                break;
            }
        }
    }

    return sb.toString();
}

Above you can nicely ask Character whether a given character is a digit. Also, StringBuilder.append runs in constant amortized time unlike string concatenation which will build a copy of two concatenated strings.

Hope that helps.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.