Search notes:

std::string length() / size()

The std::string methods length() and size() return a size_t that corresponds to the number of bytes that is represented by the string.
In the following example, the size of the string "foo" is reported as 3.
The size of "René" is 5 because the source file is encoded in UTF-8 and the *é* requires two bytes.
The size of "abc" "\x00" "def" is reported as 7 although it contains a zero byte. This is because in a std::string, a zero byte has no special meaning, unlike in a (char*) C-string. (Of course, when c_str() is used, the zero byte has a special meaning because c_str() returns a char*).
#include <string>
#include <iostream>

void printLength(const std::string& s) {
     std::cout << "length of " << s << ": " << s.length() << std::endl;
}

int main() {

    std::string foo         ("foo"                );
    std::string name        ("René"               );
    std::string containsZero("abc" "\x00" "def", 7);


    printLength(foo         );
    printLength(name        ); // 5, because source file is UTF-8 encoded
    printLength(containsZero); // 7, the zero byte is not special in std::string

 // std::cout << containsZero.c_str() << std::endl;
}
Github repository about-cpp-standard-library, path: /string/size-length.cpp

Index