Distinguish float and integer types from string

Jacob Shtokolov jacob.100205 at gmail.com
Sat Mar 9 18:11:09 UTC 2019


Hi,

Recently, I was trying to solve some funny coding challenges 
(https://www.techgig.com).
The questions were really simple, but I found it interesting 
because the website allows to use D.

One of the task was to take a string from STDIN and detect its 
type.
There were a few options: Float, Integer, string and "something 
else" (which, I think, doesn't have any sense under the scope of 
the task).

Anyway, I was struggling to find a built-in function to 
distinguish float and integer types from a string.

I came to the following solution:

```
import std.stdio;
import std.range;
import std.conv;
import std.string;
import std.format;

immutable msg = "This input is of type %s";

void main()
{
     string type;
     auto data = stdin.byLine.takeOne.front;

     if (data.isNumeric) {
         type = data.indexOf(".") >= 0 ? "Float" : "Integer";
     }
     else {
         type = "string";
     }

     writeln(msg.format(type));
}
```

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

```
if (is_integer($data)) {
     //...do smth
}
else if (is_float($data)) {
     //...do smth
}
else {
     //...do smth
}
```

I tried to use std.conv.to and std.conv.parse, but found that 
they can't really do this. When I call `data.to!int`, the value 
of "123.45" will be converted to int!

Is there any built-in way to detect these types?

Thanks!


More information about the Digitalmars-d-learn mailing list