开发者

C++11 char16_t strlen-equivalent function

开发者 https://www.devze.com 2023-03-01 12:34 出处:网络
I have a simple q开发者_如何学运维uestion: Is there a way to do a strlen()-like count of characters in zero-terminated char16_t array?use

I have a simple q开发者_如何学运维uestion: Is there a way to do a strlen()-like count of characters in zero-terminated char16_t array?


use

char_traits<char16_t>::length(your_pointer)

see 21.2.3.2 struct char_traits<char16_t> and table 62 of the C++11-Std.


Use pointers :), create a duplicate pointer to the start, then loop through it while (*endptr++);, then the length is given by endptr - startptr. You can actually template this, however, its possible the the compile won't generate the same intrinsic code it does for strlen(for different sizes ofc).


Necrolis answer includes the NULL byte in the length, which probably is not what you want. strlen() does not include the NULL byte in the length.

Adapting their answer:

static size_t char16len(uint16_t *startptr)
{
        uint16_t *endptr = startptr;
        while (*endptr) {
                endptr++;
        }
        return endptr - startptr;
}

I realize there is an accepted C++ answer, but this answer is useful for anyone who stumbles on this post using C (like I did).

0

精彩评论

暂无评论...
验证码 换一张
取 消