VS string类型字符串的长度的三种获取方法

(1).用string的成员方法length()获取字符串长度
               length()比较直观,表示的就是该字符串的长度。

#include <string>  
#include <iostream>  
   
using namespace std;  
int main()  
{  
    string str = "my string";  
    cout << str.length() << endl;  
    return 0;  
}  

(2).用string的成员方法size()获取字符串长度

           size()表示的是string这个容器中的元素个数。如果使用过std::vector之类的容器的话,可以把string看做是一个vector<char> (这里只是举例,并不能等价), char就是这个容器的元素类型。那么size()表示的就是这个vector(容器)中char的个数。

#include <string>  
#include <iostream>  
   
using namespace std;  
int main()  
{  
    string str = "Test string";  
    cout << str.size() << endl;  
    return 0;  
}  


(3).用strlen获取字符串长度

strlen同样也可以用于C++的string。但是需要用c_str()将C++ string转换为char*类型。

#include <string>  
#include <iostream>  
   
using namespace std;  
int main()  
{  
    string str = "Test string"; 
    int len = strlen(str.c_str()); 
    cout << len << endl;  
    return 0;  
}  

原文链接:https://blog.csdn.net/fanyun_01/article/details/79122843

                  本文已经把原文的第三种方法写出来了
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值