March 24, 2006
Rory Starkweather wrote:
> Oskar Linde wrote:
>> Derek Parnell wrote:
>>
>>
>>> BTW, using the foreach this way can be misleading. The pointer value
>>> returned represents the number of dchars examined and *not* an index into
>>> theString. This is significant if theString is not a dchar[].
>>
>>
>> That is not correct. The index returned is an index into the char[] array,
>> not the number of dchars processed:
>>
>> void main() {
>>         foreach(uint ix, dchar c; "åäö"c)
>>                 writefln("c = %s, ix = %s",c,ix);
>> }
>>
>> Prints:
>>
>> c = å, ix = 0
>> c = ä, ix = 2
>> c = ö, ix = 4
>>
>> /Oskar
> 
> 
>  I'm having some trouble understanding this implementation of the 'foreach' construct. From the definiton of the'foreach' expression, the purpose of the 'c' in . . .; "åäö"c) is not clear to me. Does this implicitly declare an array of items with the same data type as 'c'? In other words, three dchars in this case? From Oskar's comment that seems unlikely.

No, the c is a suffix to the string literal, defining it as a  char[]. Other suffixes are w and d for wchar[] and dchar[] respectively. Here follows a clearer version (with longer variable names ;) ):

void main() {
	char[] string = "åäö"; // contains 6 UTF-8 code units
        foreach(uint index, dchar character; string)
                writefln("character = %s, index = %s",character,index);
}

In this case, the c suffix is superfluous since the data type of string (char[])  makes the conversion implicit.

/Oskar
March 24, 2006
follows a clearer version (with longer variable names ;) ):
> 
> void main() {
>     char[] string = "åäö"; // contains 6 UTF-8 code units
>         foreach(uint index, dchar character; string)
>                 writefln("character = %s, index = %s",character,index);
> }
> 
> In this case, the c suffix is superfluous since the data type of string (char[])  makes the conversion implicit.
> 
> /Oskar

So this is like using & after a number in VB to say that it is type Long? I thought that kind of thing was only used in languages that didn't require variable type declarations. I can see how it would come in handy though.

 Thanks.
March 24, 2006
On Fri, 24 Mar 2006 19:05:30 +1100, Oskar Linde <olREM@OVEnada.kth.se> wrote:

> Derek Parnell wrote:
>
>> BTW, using the foreach this way can be misleading. The pointer value
>> returned represents the number of dchars examined and *not* an index into
>> theString. This is significant if theString is not a dchar[].
>
> That is not correct. The index returned is an index into the char[] array,
> not the number of dchars processed:
>
> void main() {
>         foreach(uint ix, dchar c; "åäö"c)
>                 writefln("c = %s, ix = %s",c,ix);
> }
>
> Prints:
>
> c = å, ix = 0
> c = ä, ix = 2
> c = ö, ix = 4
>
> /Oskar

Thanks. It didn't used to be this way, I believe.

-- 
Derek Parnell
Melbourne, Australia
1 2 3 4
Next ›   Last »