C++中获取字符串长度的方法有:字符串对象方法:string::size() 和 string::length(),返回不含终止符 '\0' 的字符个数;指针操作:遍历字符串直到遇到 '\0',计算字符个数。

C++ 中字符串的长度获取方式
在 C++ 中,字符串是字符序列,需要了解其长度才能进行有效的处理。以下介绍两种获取字符串长度的方法:
1. 字符串对象方法:
- string::size():返回字符串中字符的个数,不包含终止符 '\0'。
- string::length():等同于 string::size()。
示例:
立即学习“C++免费学习笔记(深入)”;
#include#include int main() { std::string str = "Hello, world!"; std::cout << "Length of the string: " << str.size() << std::endl; std::cout << "Length of the string: " << str.length() << std::endl; return 0; }
输出:
Length of the string: 13 Length of the string: 13
2. 指针操作:
使用指针遍历字符串,直到遇到终止符 '\0',计算字符的个数。
示例:
立即学习“C++免费学习笔记(深入)”;
#includeint main() { const char* str = "Hello, world!"; int length = 0; while (*str != '\0') { length++; str++; } std::cout << "Length of the string: " << length << std::endl; return 0; }
输出:
Length of the string: 13











