在C++中,可以使用std::string类的length()函数或者size()函数来计算字符串的长度。
以下是使用length()函数的例子:
#include <iostream>#include <string>int main() { std::string str = "Hello, World!"; int length = str.length(); std::cout << "字符串的长度为:" << length << std::endl; return 0;}以下是使用size()函数的例子:
#include <iostream>#include <string>int main() { std::string str = "Hello, World!"; int length = str.size(); std::cout << "字符串的长度为:" << length << std::endl; return 0;}无论哪种方法,都会返回字符串中字符的数量,包括空格和标点符号。

