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

Ola Fosheim Grøstad ola.fosheim.grostad at gmail.com
Sat Dec 11 09:25:37 UTC 2021


On Saturday, 11 December 2021 at 08:46:32 UTC, forkit wrote:
> On Saturday, 11 December 2021 at 08:05:01 UTC, Ola Fosheim 
> Grøstad wrote:
>>
>> Using libraries can trigger hidden allocations.
>
> ok. fine. no unnecessary, hidden allocations then.
>
> // ------------------
>
> module test;
>
> import core.stdc.stdio : putchar;
>
> nothrow @nogc void main()
> {
>     string str = "abc;def;ab";
>
>     ulong len = str.length;
>
>     for (ulong i = 0; i < len; i++)
>     {
>         if (cast(int) str[i] != ';')
>             putchar(cast(int) str[i]);
>     }
> }
>
> // ------------------

```putchar(…)``` is too slow!


```

@safe:

extern (C) long write(long, const void *, long);


void donttrythisathome(string s, char stripchar) @trusted {
	import core.stdc.stdlib;
     char* begin = cast(char*)alloca(s.length);
     char* end = begin;
     foreach(c; s) if (c != stripchar) *(end++) = c;
     write(0, begin, end - begin);
}


@system
void main() {
     string str = "abc;def;ab";
     donttrythisathome(str, ';');
}
````



More information about the Digitalmars-d-learn mailing list