Logo

Programming-Idioms

  • Rust
  • Lua
  • 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.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]*");

This uses a regular expression.
boolean b = s.matches("[0-9]+");
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("\\d+");
let b = s.bytes().all(|c| c.is_ascii_digit());

only return true for ASCII digits
let chars_are_numeric: Vec<bool> = s.chars()
				.map(|c|c.is_numeric())
				.collect();
let b = !chars_are_numeric.contains(&false);

Note that is_numeric is not just 0 -> 9.
See documentation for more info.
let b = s.chars().all(char::is_numeric);
b = tonumber(s) ~= nil

you could use pattern too
B := (for all Char of S => Char in '0' .. '9');

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