length of string result not as expected

Jonathan M Davis jmdavisProg at gmx.com
Tue Aug 13 19:59:44 PDT 2013


On Wednesday, August 14, 2013 04:53:34 jicman wrote:
> Greetings.
> 
> import std.stdio;
> 
> void main()
> {
> char[] str = "不良反應事件和產品客訴報告"; // 13 chinese characters...
> writefln(str.length);
> }
> 
> this program returns 39. I expected to return 13. How do I know
> the exact length of the characters that I have in a char[]
> variable? Thanks.

length gives you the length of the array, which is 39, because it contains 39 
chars. If you want to know the number of code points in the string as opposed 
to the number of code units (char is a UTF-8 code unit), then use 
std.range.walkLength. e.g.

writeln(walkLength(str));

It'll iterate through the string and count up the number of code points.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list