我已经将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)
Run Code Online (Sandbox Code Playgroud)s.c_str();
此代码s对转换等实际上没有副作用.您想进一步处理结果.
代替
Run Code Online (Sandbox Code Playgroud)cout<<strlen(s);
你想拥有
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)).