Distinguish float and integer types from string

Soulsbane paul at acheronsoft.com
Mon Mar 11 07:34:38 UTC 2019


On Saturday, 9 March 2019 at 18:11:09 UTC, Jacob Shtokolov wrote:
> 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!

Unless I'm missing something perhaps two functions like this:

bool isInteger(string value) pure nothrow @safe
{
	import std.string : isNumeric;
	return (isNumeric(value) && value.count(".") == 0) ? true : 
false;
}

bool isDecimal(string value) pure nothrow @safe
{
	import std.string : isNumeric;
	return (isNumeric(value) && value.count(".") == 1) ? true : 
false;
}




More information about the Digitalmars-d-learn mailing list