Determine if a string is numeric: Difference between revisions

Updted for D2
(added Fantom example)
(Updted for D2)
Line 254:
 
=={{header|D}}==
<lang d>import std.stdio, std.string, std.conv, std.regexp;
 
bool isNumeric(string s) {
try
toDoubleto!real(s.strip());
catch (ErrorConvException e)
return false;
return true;
}
 
boolvoid isIntmain(string s) {
foreach (is; ["12", c;" s)12\t", {"hello12", "-12", "02",
if (i == 0 && (c == '-' || c"0-12", == '"+')12", "1.5"])
writeln(`isNumeric("`, s, `") = continue`, isNumeric(s));
if (c >= '0' && c <= '9')
continue;
return
false;
}
return true;
}
 
writeln("\nNo hex or binary conversion:");
bool isInt2(string s) {
returnforeach cast(bool)search(s; ["0x10", r"^[-+]?\d+$6b"]);
writeflnwriteln("`isNumeric("`, s, `") = "`, isNumeric(s));
}
}</lang>
Output:
<pre>isNumeric("12") = true
isNumeric(" 12 ") = true
isNumeric("hello12") = false
isNumeric("-12") = true
isNumeric("02") = true
isNumeric("0-12") = false
isNumeric("+12") = true
isNumeric("1.5") = true
 
No hex or binary conversion:
bool isInt3(string s) {
isNumeric("0x10") = false
try
isNumeric("6b") = false</pre>
toInt(s.strip());
catch (Error e)
return false;
return true;
}
 
void main() {
foreach (s; ["12", " 12\t", "hello12", "-12", "0-12", "+12", "0x10", "6b"]) {
writefln("isNumeric(", s, ") = ", isNumeric(s));
writefln("isInt(", s, ") = ", isInt(s));
writefln("isInt2(", s, ") = ", isInt2(s));
writefln("isInt3(", s, ") = ", isInt3(s));
writefln();
}
}</lang>
 
=={{header|E}}==
Anonymous user