SlicedString Length
Salih Dincer
salihdb at hotmail.com
Fri Oct 20 20:29:56 UTC 2023
Good news!
I collected them in a template with the condition of running
split() once at compile time. The result seems perfect? What
are your thoughts?
```d
void main()
{
auto slc = sliceOff!"abc def ghi";
auto len = slc.length;
slc.index = len;
import std.stdio, std.algorithm: equal;
assert(slc.equal(["abc", "def", "ghi"]));
foreach(s; slc) s.write;
writeln; // abcdefghi
// Push Test
with(slc)
{
string test = "jkl";
push(test);
auto p = elementsPos[$ - 1];
assert(data[p[0]..p[1]] == test);
}
foreach(s; slc) s.write;
writeln; // abcdefghijkl
auto tmp = slc.dup;
assert(tmp.front == "abc");
tmp.popFront;
assert(slc.front == "abc");
assert(tmp.front == "def");
}
template sliceOff(string STR, string SEP = " ")
{
auto sliceOff()
{
SlicedString s;
s.popFront();
return s;
}
import std.array : split;
import std.range : walkLength;
enum LEN = STR.split(SEP).walkLength;
struct SlicedString
{
long index, back, next = -1;
size_t len = LEN;
string data = STR;
auto push(string data)
{
this.data ~= SEP ~ data;
len++;
index++;
}
auto elementsPos()
{
long[][] result;
auto r = this.dup;
while(!r.empty)
{
result ~= [r.back, r.next];
r.popFront();
}
return result;
}
alias dup = save;
auto save() { return this; }
auto length() { return len; }
bool empty() { return index == 0; }
auto front() { return data[back..next]; }
void popFront()
{
import std.string : find = indexOf;
--index;
back = ++next;
next = data.find(SEP, next);
if(next == -1)
{
next = data.length;
}
}
}
}
```
SDB at 79
More information about the Digitalmars-d-learn
mailing list