Char[] confusing

Lutger lutger.blijdestijn at gmail.com
Mon Mar 2 14:34:40 PST 2009


Qian Xu wrote:

> Hi,
> 
> I am confusing with getting sub-string of a char[].
> 
> ------------------------- code ---------------------------------
> module main;
> 
> import tango.io.Console;
> import tango.text.convert.Integer;
> 
> void main()
> {
>    char[] s = "ABCDE"; // 5 chars
>    int len = s.length;
>    Cout("s='" ~ s ~ "', length=" ~ toString(len)).newline;
>    Cout("s[" ~ toString(len-1) ~ "]= " ~ s[len-1]).newline;
>    Cout("s[0 .. " ~ toString(len-1) ~ "]= " ~ s[0 .. len-1]).newline;
>    Cout("s[0 .. " ~ toString(len) ~ "]= " ~ s[0 .. len]).newline;
>    Cout("s[1 .. " ~ toString(len-1) ~ "]= " ~ s[1 .. len-1]).newline;
>    Cout("s[1 .. " ~ toString(len) ~ "]= " ~ s[1 .. len]).newline;
> }
> ------------------------- code ---------------------------------
> 
> The result is (dmd + windowsxp)
> 
> s='ABCDE', length=5
> s[4]= E
> s[0 .. 4]= ABCD
> s[0 .. 5]= ABCDE
> s[1 .. 4]= BCD
> s[1 .. 5]= BCDE
> 
> -------------------------------------------------------
> 
> My question is: why s[4]=E, but s[0..4]=ABCD (without E)

s[4] means the fifth element of s[]
s[0..4] is a slice from the first to the fifth, but not including the fifth 
element. The last element in a slice is always one past the end of that 
slice. 



More information about the Digitalmars-d-learn mailing list