Thread overview
Convering strings containing number
Jun 15, 2022
Salih Dincer
Jun 15, 2022
Mike Parker
Jun 16, 2022
Salih Dincer
June 15, 2022

Hi,

I've been interested in conversion possibilities for a while. I tried to convert a string containing numbers but with no success in single digits. The only solution I found is to subtract 48 from the result:

import std;
void main()
{
    string str = "abc123";
    str[3..$].to!int.writeln; // 123
    auto bar = str[3].to!int;
    assert(bar == 49); // 49 is value for ASCII.
    writeln(bar - 48); // 1
}
June 15, 2022

On Wednesday, 15 June 2022 at 04:26:44 UTC, Salih Dincer wrote:

>

Hi,

I've been interested in conversion possibilities for a while. I tried to convert a string containing numbers but with no success in single digits. The only solution I found is to subtract 48 from the result:

import std;
void main()
{
    string str = "abc123";
    str[3..$].to!int.writeln; // 123
    auto bar = str[3].to!int;
    assert(bar == 49); // 49 is value for ASCII.
    writeln(bar - 48); // 1
}

By indexing str, you're getting a char. So to is operating on that rather than on a string. Slicing will give you what you want, since then you'd have a "1" rather than a '1':

str[3..4].to!int;
June 16, 2022

On Wednesday, 15 June 2022 at 04:39:21 UTC, Mike Parker wrote:

>
str[3..4].to!int;

Thanks, I got the solution based on your answer. I also created different slicing functions. They work just fine without the need for conversion:

    T solKes(string str, size_t a, size_t l)
    {
      import std.conv;
      const b = a + l;
      return str[a + 1..b].to!T;
    }

    T kalKes(string str, size_t a, size_t l)
    {
      import std.conv;
      const b = a + l;
      return str[b - 1..b].to!T;
    }

    T sagKes(string str, size_t a, size_t l)
    {
      import std.conv;
      const b = a + l;
      return str[a..b - 1].to!T;
    }

    T tekKes(string str, size_t a, size_t l)
    {
      import std.conv;
      return str[a..a + l].to!T;
    }

Thanks again...

SDB@79