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

Ola Fosheim Grøstad ola.fosheim.grostad at gmail.com
Sat Dec 11 08:26:59 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 ;)

Scanning short strings twice is not all that expensive as they 
will stay in the CPU cache when you run over them a second time.

```
import std.stdio;

@safe:

string stripsemicolons(string s) @trusted {
     int i,n;
     foreach(c; s) n += c != ';'; // premature optimization
     auto r = new char[](n);
     foreach(c; s) if (c != ';') r[i++] = c;
     return cast(string)r;
}

int main() {
	writeln(stripsemicolons("abc;def;ab"));
     return 0;
}
```



More information about the Digitalmars-d-learn mailing list