Check String Has Only Digits
Check whether a string contains only numeric digits.
Sample input
12345
Sample output
true
Solution
s = "12345"
print(s.isdigit())
const s = "12345";
console.log(/^\d+$/.test(s));
public class Main {
public static void main(String[] args) {
String s = "12345";
boolean allDigits = s.matches("\\d+");
System.out.println(allDigits);
}
}
fun main() {
val s = "12345"
println(s.isNotEmpty() && s.all { it.isDigit() })
}
let s = "12345"
let allDigits = !s.isEmpty && s.allSatisfy { $0.isNumber }
print(allDigits)
void main() {
String s = '12345';
bool allDigits = RegExp(r'^\d+$').hasMatch(s);
print(allDigits);
}
#include <iostream>
#include <cctype>
using namespace std;
int main() {
string s = "12345";
bool allDigits = !s.empty();
for (char c : s) {
if (!isdigit(c)) {
allDigits = false;
break;
}
}
cout << (allDigits ? "true" : "false") << endl;
return 0;
}
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
char s[] = "12345";
int allDigits = strlen(s) > 0;
for (int i = 0; s[i]; i++) {
if (!isdigit(s[i])) {
allDigits = 0;
break;
}
}
printf("%s\n", allDigits ? "true" : "false");
return 0;
}