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));
                result += c;

        return result;

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


1 Answer 1


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)) {

            if (sb.length() == 2) {

    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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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