Does string.isNumeric mean that parse!int will not throw?

w0rp devw0rp at gmail.com
Thu Feb 20 11:46:34 PST 2014


On Thursday, 20 February 2014 at 19:23:28 UTC, Cooler wrote:
> On Thursday, 20 February 2014 at 19:18:15 UTC, Stanislav Blinov
> wrote:
>> On Thursday, 20 February 2014 at 19:11:55 UTC, Cooler wrote:
>>> The code:
>>>
>>> string s = "...";
>>> if(s.isNumeric){
>>>   auto x = parse!int(s); // Can I be sure here that parse will
>>> not throw?
>>> }
>>
>> No. s may still contain data that is not convertible to int. 
>> For
>> example, "nan".
>
> Is there any way to know that a string is convertible to a 
> number
> without throwing?

You could do this.

import std.stdio;
import std.algorithm: all;
import std.ascii: isDigit;

void main(string[] args) {
      writeln("123".all!isDigit); // true
      writeln("12x".all!isDigit); // false
}

Combine the "all" algorithm which returns true if everything in a
range matches a predicate and use "isDigit" as the predicate
which returns true if the character is an ascii digit.

if (s.length > 0 && s.all!isDigit) {
      // Never throws now.
      auto x = parse!int(s);
}


More information about the Digitalmars-d-learn mailing list