Search code examples
d

Parsing a substring without allocating it separately


I have a string containing a nondigit followed by digits. For example:

string s = "A42";

How do I obtain a char (containing the nondigit) and an int (obtained by parsing the digits) from this string, without allocating a second temporary string?

char c = 'A';
int i = 42;

Solution

  • A slice of the string is an allocation of two pointers into the original string (or a pointer and a length), as normal for D arrays. So this is enough:

    char c = s[0];
    int i = to!int(s[1..$]);