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

BoQsc vaidas.boqsc at gmail.com
Wed Dec 8 13:01:32 UTC 2021


On Wednesday, 8 December 2021 at 11:35:39 UTC, Biotronic wrote:
> On Wednesday, 8 December 2021 at 11:23:45 UTC, BoQsc wrote:
>> Let's say I want to skip characters and build a new string.
>>
>> The string example to loop/iterate:
>>
>> ```
>> import std.stdio;
>>
>> void main()
>> {
>>     string a="abc;def;ab";
>>
>> }
>> ```
>>
>> The character I want to skip: `;`
>>
>> Expected result:
>> ```
>> abcdefab
>> ```
> [..]
>         string b = a.filter!(c => c != ';').to!string;
>         writeln(b);
>     }

I somehow have universal cross language hate for this kind of 
algorithm.
I'm not getting used to the syntax and that leads to poor 
readability.
But that might be just me.

Anyways,
Here is what I've come up with.

```
import std.stdio;

void main()
{
     string a = "abc;def;ab";
	string b;
	
	for(int i=0; i<a.length; i++){
		write(i);
		writeln(a[i]);
		if (a[i] != ';'){
			b ~= a[i];
		}
		
	}
	
     writeln(b);
}
```


More information about the Digitalmars-d-learn mailing list