用于c ++中的字符串的strlen

Ish*_*sal -3 c++ string stl

我已经将c ++转换为c类型字符串并使用strlen但它无法正常工作.

 #include<bits/stdc++.h>
using namespace std;
int main(){
string s("Hello");
s.c_str();
cout<<strlen(s);
}
Run Code Online (Sandbox Code Playgroud)

πάν*_*ῥεῖ 5

s.c_str();
Run Code Online (Sandbox Code Playgroud)

此代码s对转换等实际上没有副作用.您想进一步处理结果.

代替

cout<<strlen(s);
Run Code Online (Sandbox Code Playgroud)

你想拥有

cout<<strlen(s.c_str());
Run Code Online (Sandbox Code Playgroud)

要么

cout<<s.size();
Run Code Online (Sandbox Code Playgroud)

其中后者肯定更有效率,因为标准要求O(1)的时间复杂度std::string::size(),在这里strlen()不能保证比时间复杂度更好O(strlen(s)).