How to get the number of characters in a std::string?

前端 未结 12 990
既然无缘
既然无缘 2020-11-28 03:52

How should I get the number of characters in a string in C++?

12条回答
  •  -上瘾入骨i
    2020-11-28 04:48

    In C++ std::string the length() and size() method gives you the number of bytes, and not necessarily the number of characters !. Same with the c-Style sizeof() function!

    For most of the printable 7bit-ASCII Characters this is the same value, but for characters that are not 7bit-ASCII it's definitely not. See the following example to give you real results (64bit linux).

    There is no simple c/c++ function that can really count the number of characters. By the way, all of this stuff is implementation dependent and may be different on other environments (compiler, win 16/32, linux, embedded, ...)

    See following example:

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    int main()
    {
    /* c-Style char Array */
    const char * Test1 = "1234";
    const char * Test2 = "ÄÖÜ€";
    const char * Test3 = "αβγ

提交回复
热议问题