我应该如何在 C++ 中获取字符串中的字符数?
最佳答案
如果您使用 std::string
,请调用 length()
:
std::string str = "hello";
std::cout << str << ":" << str.length();
// Outputs "hello:5"
如果您使用的是 c 字符串,请调用 strlen()
.
const char *str = "hello";
std::cout << str << ":" << strlen(str);
// Outputs "hello:5"
或者,如果您碰巧喜欢使用 Pascal 样式的字符串(或 f***** 字符串,如 Joel Spolsky likes to call them,当它们有一个尾随 NULL 时),只需取消对第一个字符的引用。
const char *str = "\005hello";
std::cout << str + 1 << ":" << *str;
// Outputs "hello:5"
关于c++ - 如何获取 std::string 中的字符数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/905355/