Thread overview
foreach over string
May 24, 2014
Kagamin
May 24, 2014
Etienne Cimon
May 24, 2014
Ali Çehreli
May 24, 2014
John Colvin
May 24, 2014
Kagamin
May 24, 2014
Kagamin
May 24, 2014
foreach over string apparently iterates over chars by default instead of dchars. Didn't it prefer dchars?

string s="weiß";
int i;
foreach(c;s)i++;
assert(i==5);
May 24, 2014
On 2014-05-24 12:46, Kagamin wrote:
> foreach over string apparently iterates over chars by default instead of
> dchars. Didn't it prefer dchars?
>
> string s="weiß";
> int i;
> foreach(c;s)i++;
> assert(i==5);


A string is defined by:
alias string = immutable(char)[];

It doesn't add anything to that type (unless you import a library like std.algorithm, which adds many "methods" thanks to UFCS and generic functions)

I believe you are looking for dstring which is defined by:
alias dstring = immutable(dchar)[];

dstring s="weiß";
int i;
foreach(c;s)i++;
assert(i==4);
May 24, 2014
On 05/24/2014 09:46 AM, Kagamin wrote:
> foreach over string apparently iterates over chars by default instead of
> dchars. Didn't it prefer dchars?

I don't think so. The range algorithms iterate by dchar though.

>
> string s="weiß";
> int i;
> foreach(c;s)i++;
> assert(i==5);

Ali

May 24, 2014
On Saturday, 24 May 2014 at 16:46:42 UTC, Kagamin wrote:
> foreach over string apparently iterates over chars by default instead of dchars. Didn't it prefer dchars?
>
> string s="weiß";
> int i;
> foreach(c;s)i++;
> assert(i==5);

Nope.

if you use foreach(dchar c; s) you will get the iteration by code-point you are looking for.
May 24, 2014
Ah, yeah, found this: http://forum.dlang.org/thread/mailman.266.1319139465.24802.digitalmars-d@puremagic.com
May 24, 2014
On Saturday, 24 May 2014 at 18:18:37 UTC, John Colvin wrote:
> if you use foreach(dchar c; s) you will get the iteration by code-point you are looking for.

Actually I was trying to prevent decoding :) It just occurred to me it can be tricky in generic code.