length of string result not as expected

Jacob Carlborg doob at me.com
Wed Aug 14 00:20:15 PDT 2013


On 2013-08-14 05:05, Adam D. Ruppe wrote:

> Your code looks like D1...
>
> in D1 or D2:
> import std.uni;
> dstring s2 = toUTF32(str);
> writeln(s2.length); // 13
>
>
> in D2 you can do it a little more efficiently like this:
>
> import std.range;
> writeln(walkLength(str)); // 13

In D1 you can easily implement walkLength yourself:

import std.utf;

size_t walkLength (C) (C[] arr)
{
     size_t i;
     size_t len;

     while (i < arr.length)
     {
         i += arr.stride(i);
         len++;
     }

     return len;
}

void main ()
{
     auto a = "不良反應事件和產品客訴報告";
     assert(walkLength(a) == 13);
}

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list