On Saturday, 10 December 2016 at 03:51:34 UTC, brocolis wrote:
How do I separate IP parts with dlang?
I found this very cool trick, with C++:
http://stackoverflow.com/a/5328190
std::string ip ="192.168.1.54";
std::stringstream s(ip);
int a,b,c,d; //to store the 4 ints
char ch; //to temporarily store the '.'
s >> a >> ch >> b >> ch >> c >> ch >> d;
std::cout << a << " " << b << " " << c << " "<< d;
I wonder what's the equivalent D code.
Not much of a trick, but:
import std.algorithm : splitter, map;
import std.range : take;
import std.conv : to;
import std.array : array;
string ip = "192.168.1.54";
auto parts = ip
.splitter('.')
.take(4)
.map!((a) => a.to!int)
.array;
assert(parts[0] == 192);
assert(parts[1] == 168);
assert(parts[2] == 1);
assert(parts[3] == 54);
Remove the .array to keep it lazy, but then you can't index it
for the values, only walk through them in a foreach.