How to convert a char* pointer into a C++ string?
Solution 1
- To get the
C
string equivalent of theC++
string
object usec_str
function.
- To locate the first occurence of a
char
in astring
object usefind_first_of
function.
Example:
string s = "abc";
// call to strlen expects char *
cout<<strlen(s.c_str()); // prints 3
// on failure find_first_of return string::npos
if(s.find_first_of('a') != string::npos)
cout<<s<<" has an a"<<endl;
else
cout<<s<<" has no a"<<endl;
Note: I gave the strlen
just an example of a function that takes char*
.
Solution 2
You can't get a char*
from a string
string
does not allow you free access to its internal buffer.
The closest you can get is a const char*
using .c_str()
if you want it null terminated or .data()
if it doesn't have to be null terminated.
You can then cast the pointer returned by these functions to char*
but you do this on your own risk. That being said this is a relatively safe cast to make as long as you make sure you're not changing the string. If you changed it then the pointer you got from c_str()
may no longer be valid.
This code:
string str("Hello World!");
char* sp = (char*)str.c_str();
sp[5] = 'K';
is probably ok
However this:
string str("Hello World!");
char* sp = (char*)str.c_str();
str = "Chaged string";
sp[5] = 'K';
is most definitely not ok.
Moeb
Updated on June 14, 2020Comments
-
Moeb almost 4 years
I have a C++
string
. I need to pass this string to a function accepting achar*
parameter (for example -strchr()
).a) How do I get that pointer?
b) Is there some function equivalent to
strschr()
that works forC++ strings
? -
Carl Smotricz about 14 yearsAre you sure it's
c_tsr
and notc_str
? I'm no C++ expert but I Googled forc_tsr
and was corrected toc_str
. -
Admin about 14 yearsWrong. c_str() returns a const char *
-
JRL about 14 years@Neil: it's an example, jeez... but I've edited it for your pleasure ;-)
-
Moeb about 14 years@unicornaddict: thanks. now how do I find the other occurrences of that character in the string? [the length of the string is huge, so creating a whole new string is not an option]
-
codaddict about 14 years@cambr: There is a overloaded version of
find_first_of
which accepts the position to start the search from as an argument. I've posted an example here: ideone.com/bESwL -
Justin Ardini about 14 yearsThis isn't a very good idea. There's no guarantee that pw will point to the same data at a later point, even if some_string is still around. It's much safer to call c_str() to each function you need to pass a char*.
-
a paid nerd over 13 years+1 for this being the answer to the question I was searching for :)
-
a paid nerd over 13 yearsMore discussion here: bytes.com/topic/c/answers/…
-
Frerich Raabe over 10 yearsYou can avoid manual memory management by doing
std::vector<char> charBuf(yourString.begin(), yourString.end()); charBuf.push_back('\0');
- this will let you use&charBuf[0]
to get achar*
.