How to loop through characters of a string in D language?

Ola Fosheim Grøstad ola.fosheim.grostad at gmail.com
Mon Dec 13 09:36:57 UTC 2021


On Friday, 10 December 2021 at 18:47:53 UTC, Stanislav Blinov 
wrote:
> Threshold could be relative for short strings and absolute for 
> long ones. Makes little sense reallocating if you only waste a 
> couple bytes, but makes perfect sense if you've just removed 
> pages and pages of semicolons ;)

Like this?

```
@safe:

string prematureoptimizations(string s, char stripchar) @trusted {
     import core.memory;
     immutable uint flags = 
GC.BlkAttr.NO_SCAN|GC.BlkAttr.APPENDABLE;
     char* begin = cast(char*)GC.malloc(s.length+1, flags);
     char* end = begin + 1;
     foreach(c; s) {
         immutable size_t notsemicolon = c != stripchar;
         // hack: avoid conditional by writing semicolon outside 
buffer
         *(end - notsemicolon) = c;
         end += notsemicolon;
     }
     immutable size_t len = end - begin - 1;
     begin = cast(char*)GC.realloc(begin, len, flags);
     return cast(string)begin[0..len];
}

void main() {
     import std.stdio;
     string str = "abc;def;ab";
     writeln(prematureoptimizations(str, ';'));
}

```


More information about the Digitalmars-d-learn mailing list