租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

c++怎么计算字符串长度,c++计算字符长度

发布时间:2023-10-28 00:52:25

c++怎样计算字符串长度

在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;
}

不管哪一种方法,都会返回字符串中字符的数量,包括空格和标点符号。