扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

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

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

扫码添加客服微信