digitalmars.D.learn - Convering strings containing number
- Salih Dincer (16/16) Jun 14 2022 Hi,
- Mike Parker (7/23) Jun 14 2022 By indexing `str`, you're getting a `char`. So `to` is operating
- Salih Dincer (31/34) Jun 16 2022 Thanks, I got the solution based on your answer. I also created
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:
```d
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
}
```
Jun 14 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:
```d
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'`:
```d
str[3..4].to!int;
```
Jun 14 2022
On Wednesday, 15 June 2022 at 04:39:21 UTC, Mike Parker wrote:```d 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: ```d 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
Jun 16 2022








Salih Dincer <salihdb hotmail.com>