小编典典

如何获取 std::string 中的字符数?

c++

我应该如何在 C++ 中获取字符串中的字符数?


阅读 373

收藏
2022-04-15

共1个答案

小编典典

如果您使用的是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喜欢在它们有尾随 NULL 时调用它们),只需取消引用第一个字符。

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