Elliot Elliot - 1 year ago 174
C++ Question

C++ String Length?

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

Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download