I have converted c++ to c type string and working with strlen but it is not working.
#include<bits/stdc++.h>
using namespace std;
int main(){
string s("Hello");
s.c_str();
cout<<strlen(s);
}
I have converted c++ to c type string and working with strlen but it is not working.
#include<bits/stdc++.h>
using namespace std;
int main(){
string s("Hello");
s.c_str();
cout<<strlen(s);
}
s.c_str();
This code has no side effects on s
actually regarding a conversion or such. You want to process the result further.
Instead of
cout<<strlen(s);
you want to have either
cout<<strlen(s.c_str());
or
cout<<s.size();
Where the latter is the certainly more efficient, because the standard requires a time complexity of O(1) for std::string::size()
, where strlen()
cannot guarantee a better time complexity than O(strlen(s))
.
If you want to waste clock-cycles in your processor:
cout << strlen(s.c_str());
will count every character up to the first nul character in s
.
If you just want to know how long the string is:
cout << s.length();
or
cout << s.size();
will give you that (and with an algorithm that is O(1)
rather than the strlen
algorithm that is O(n)
- meaning that a million character long string takes one million times longer to measure the length of than a single character string). [Of course, if you have a std::string
that contains a nul character in the middle, you may find that one of these methods is "right" and the other is "wrong" because it either gives too long or too short a length - a C style string is not allowed to contain a nul character in the middle of the string, it is only allowed as a termination]
Why use strlen
when the string
class does the business?
Please read http://en.cppreference.com/w/cpp/string/basic_string and not the size/length method
Otherwise do as the @πάντα ῥεῖ suggests