12

I have a C++ string. I need to pass this string to a function accepting a char* parameter (for example - strchr()).

a) How do I get that pointer?

b) Is there some function equivalent to strschr() that works for C++ strings?

Eagle-Eye
  • 1,468
  • 2
  • 18
  • 26
Moeb
  • 10,527
  • 31
  • 84
  • 110

8 Answers8

20
  1. To get the C string equivalent of the C++ string object use c_str function.
  2. To locate the first occurence of a char in a string object use find_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*.

codaddict
  • 445,704
  • 82
  • 492
  • 529
  • @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] – Moeb Apr 25 '10 at 12:01
  • 1
    @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: http://www.ideone.com/bESwL – codaddict Apr 25 '10 at 12:08
6

Surprisingly, std:;string has far, far more capabilities than C-style strings. You probably want the find_first_of() method. In general, if you find yourself using the strxxx() functions on C++ std::strings, you are almost certainly doing something wrong.

Like much of the C++ Standard Library, the string class is a complex beast. To make the most of it, you really need a good reference book. I recommend The C++ Standard Library, by Nicolai Josuttis.

4

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.

shoosh
  • 76,898
  • 55
  • 205
  • 325
0

The C++ Standard provides two member functions of claass std::basic_string that return pointer to the first element of the string. They are c_str() and data(). But the both return const char *, So you may not use them with a function that has parameter of type char *.

As for function strchr then its first parameter is const char *. So you may use c_str() and data() with this function. However it is much better to use member function find()of class sttd::basic_string instead of strchr.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

If str in your string use str.c_str() method to get the char* inside it.

Dror Helper
  • 30,292
  • 15
  • 80
  • 129
0

If you just want to assign a string literal to pw, you can do it like

char *pw = "Hello world";

If you have a C++ std::string object, the value of which you want to assign to pw, you can do it like

char *pw = some_string.c_str()

However, the value that pw points to will only be valid for the life time of some_string.

More here :
How to assign a string to char *pw in c++

GoodLUCK!!

Community
  • 1
  • 1
TheCodeArtist
  • 21,479
  • 4
  • 69
  • 130
  • 1
    Wrong. c_str() returns a const char * –  Apr 25 '10 at 11:27
  • This 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*. – Justin Ardini Apr 26 '10 at 01:31
0
std::string yourString("just an example");
char* charPtr = new char[yourString.size()+1];
strcpy(charPtr, yourString.c_str());
JRL
  • 76,767
  • 18
  • 98
  • 146
  • @Neil: it's an example, jeez... but I've edited it for your pleasure ;-) – JRL Apr 25 '10 at 11:48
  • You can avoid manual memory management by doing `std::vector charBuf(yourString.begin(), yourString.end()); charBuf.push_back('\0');` - this will let you use `&charBuf[0]` to get a `char*`. – Frerich Raabe Aug 28 '13 at 18:04
0

Perhaps this exmaple will help you

#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string str ("Replace the vowels in this sentence by asterisks.");
  size_t found;

  found=str.find_first_of("aeiou");
  while (found!=string::npos)
  {
    str[found]='*';
    found=str.find_first_of("aeiou",found+1);
  }

  cout << str << endl;

  return 0;
}
gameover
  • 11,813
  • 16
  • 59
  • 70