Search code examples
c++stringpointersstrchr

How to convert a char* pointer into a C++ string?


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?


Solution

    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*.