简体   繁体   中英

C++11 char16_t strlen-equivalent function

I have a simple question: 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM