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

Stanislav Blinov stanislav.blinov at gmail.com
Fri Dec 10 18:47:53 UTC 2021


On Friday, 10 December 2021 at 13:22:58 UTC, Matheus wrote:

> My C way of thinking while using D:
>
> import std;
>
> string stripsemicolons(string input){
>     char[] s = input.dup;
>     int j=0;
>     for(int i=0;i<input.length;++i){
>         if(s[i] == ';'){ continue; }
>         s[j++] = s[i];
>     }
>     s.length = j;
>     return s.idup;
> }


Oooh, finally someone suggested to preallocate storage for all 
these reinventions of the wheel :D

I would suggest instead of the final idup checking the length and 
only duplicating if certain waste threshold is broken, otherwise 
just doing 
https://dlang.org/phobos/std_exception.html#assumeUnique (or a 
cast to string). The result is unique either way.

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 ;)

Be interesting to see if this thread does evolve into a SIMD 
search...


More information about the Digitalmars-d-learn mailing list