How to loop through characters of a string in D language?
Ola Fosheim Grøstad
ola.fosheim.grostad at gmail.com
Sun Dec 12 09:25:05 UTC 2021
Of course, since it is easy to mess up and use ranges in the
wrong way, you might want to add ```assert```s. That is most
likely *helpful* to newbies that might want to use your kickass
library function:
```
auto helpfuldeatheater(char stripchar)(string str) {
struct voldemort {
immutable(char)* begin, end;
bool empty(){ return begin == end; }
char front(){ assert(!empty); return *begin; }
char back()@trusted{ assert(!empty); return *(end-1); }
void popFront()@trusted{
assert(!empty);
while(begin != end){begin++; if (*begin != stripchar)
break; }
}
void popBack()@trusted{
assert(!empty);
while(begin != end){end--; if (*(end-1) != stripchar)
break; }
}
this(string s)@trusted{
begin = s.ptr;
end = s.ptr + s.length;
while(begin!=end && *begin==stripchar) begin++;
while(begin!=end && *(end-1)==stripchar) end--;
}
}
return voldemort(str);
}
```
More information about the Digitalmars-d-learn
mailing list