Elliot Elliot - 4 months ago 30
C++ Question

C++ String Length?

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

Answer

If you're using a std::string, call length():

std::string str = "hello";
std::cout << str << ":" str.length();
// Outputs "hello:5"

If you're using a c-string, call strlen().

const char *str = "hello";
std::cout << str << ":" << strlen(str);
// Outputs "hello:5"

Or, if you happen to like using Pascal-style strings (or f***ed strings as Joel Spolsky likes to call them when they have a trailing NULL), just dereference the first character.

const char *str = "\005hello";
std::cout << str + 1 << ":" << *str;
// Outputs "hello:5"