On Saturday, 9 March 2019 at 18:11:09 UTC, Jacob Shtokolov wrote:w
One of the task was to take a string from STDIN and detect its type.

The way I'd do this is a very simple loop:

enum Type { String, Float, Int }
if(str.length && str[0] == '-') {
   str = str[1 .. $];
Type type = str.length ? Type.Int : Type.String;
foreach(ch; str) {
   if(ch == '.' && type = Type.Int)
        type = Type.Float;
   else if(ch < '0' || ch > '9') {
       type = Type.String;

And if you need to support other details, add them on top of that. For example, exponents on floats may be a second clause like how I put negative ahead.

You may also choose to use a regular expression though I think that is overkill for this.

    if (data.isNumeric) {

There are several caveats on that isNumeric function: it sees if something looks like a D numeric literal, which might not be what you want. For example, isNumeric("1UL") passes because the U and L suffixes are allowed in D literals...

But I think that's ugly. The thing is that in PHP, for example, I would do that like this:

if (is_integer($data)) {

Simiarly, this also will not od what you want. is_integer("1") will return false. "1" is of type string. Those functions check the dynamic type tag, not the contents of a string.

(actually, you arguably can just always return "string" cuz stdin is basically just a string or a binary stream anyway :P )

PHP's is_numeric returns true for both integer and floating point things, similarly to D's...

Reply via email to