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

标签 c++ string stdstring string-length

我应该如何在 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/

相关文章:

c++ - 为什么不是 std::string::max_size() == std::string::allocator::max_size()

c++ - JNI system.loadlibrary 问题 - 使用 C 库的 native C++ dll

c++ - UE4中简单坐标变换结果不正确

c++ - 每帧需要一次时 make_heap vs priority_queue 效率

C++11 内部 std::string 表示 (libstdc++)

string - Ada 字符串比较

c++ - 如何从 main ( ) 调用线程成员函数

java - 输入第二个单词

c++ - 将非英文字符串存储在 std::string 中

c++ - 在 C++11 中,将引用/指针返回到 std::string 中某个位置的最高效方法是什么?