Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #137 Check if string contains only digits

Set the boolean b to true if the string s contains only characters in the range '0'..'9', false otherwise.

boolean b = s.matches("\\d+");
String d = "0123456789";
int i, n = s.length();
boolean b = n != 0;
for (i = 0; i < n; ++i)
    if (d.indexOf(s.charAt(i)) == -1) {
        b = false;
        break;
    }
boolean b = s.matches("[0-9]*");

This uses a regular expression.
boolean b = s.chars()
    .allMatch(Character::isDigit);
if (s.length() == 0) b = false;

"... If the stream is empty then true is returned and the predicate is not evaluated."
boolean b = s.matches("[0-9]+");
B := (for all Char of S => Char in '0' .. '9');

New implementation...
< >
programming-idioms.org