How to get the length of a string in c++?

In C++, you can use the length() method of the std::string class to find the length of a string, or you can use the size() method. For example:

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

The above code will produce:

Length of string using length() method: 13
Length of string using size() method: 13
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds