温馨提示×

c++怎么求字符串的长度

c++
小亿
185
2024-03-07 18:43:21
栏目: 编程语言

在C++中,可以使用std::string类的length()方法来求字符串的长度,也可以使用size()方法来获取字符串的长度。示例如下:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    
    // 使用length()方法求字符串长度
    int len1 = str.length();
    
    // 使用size()方法求字符串长度
    int len2 = str.size();
    
    std::cout << "Length of string using length() method: " << len1 << std::endl;
    std::cout << "Length of string using size() method: " << len2 << std::endl;
    
    return 0;
}

以上代码将输出:

Length of string using length() method: 13
Length of string using size() method: 13

0