Komal Joshi
Komal Joshi

Reputation: 21

Using static_cast in character array to use string functions

I want to use static_cast to use string functions like erase() and find() in a character array, say char str[50]. For instance, please consider following segment:

char str[]="abcdefghi";
char val[]="bc";
static_cast<string>(str).erase(static_cast<string>(str).find(val[0]),1);

Please tell me if it is correct and if it is, then str is not retaining the value it should have, i.e. "acdefghi".

Upvotes: 2

Views: 6494

Answers (2)

user270049
user270049

Reputation: 109

If you want to access char* (raw c string) like an stl container this is std::experimental::string_view was invented for. But it will give an access only to read/iterate/find like operations, not modifying. There is also a sad moment - it is delayed for C++17 standard (anyway GCC-6.x already has it). See for boost::utility::string_view also. If you want to have modify access for char* I would recommend you using your own wrapper over string with length check, etc.

Here is an example I am talking about:

#include <iostream>
#include <experimental/string_view>
#include "string.h"

using namespace std;


typedef experimental::string_view string_view;

class RawStringWrapper : public string_view
{
    char * sstr;
    size_t len;

public:
    RawStringWrapper(char * str, size_t sz)
        : std::experimental::string_view(str, sz),
          sstr(str),
          len(sz){}

    bool erase(const string &s){
        auto pos = find(s);
        if (std::string::npos != pos){
            sstr[pos] = 0;
            strcat(sstr, sstr + pos + s.size());
            return true;
        }
        return false;
    }
    // ...other modifying functions you need
};

int main(int argc, char *argv[])
{
    char rawString[] = "abcdefgh";
    RawStringWrapper str(rawString, sizeof(rawString));
    str.erase("cde");
    cout << rawString << endl;
    return 0;
}

Upvotes: 0

songyuanyao
songyuanyao

Reputation: 172914

Please tell me if it is correct

It won't work.

static_cast<string>(str) will create a temporary std::string from str, its content is copied from str. Any modification on it has nothing to do with the original variable str.

You could do this on std::string, and convert it back to const char* when necessary.

string new_str(str);                    // construct std::string
new_str.erase(new_str.find(val[0]), )); // modification on it
cout << new_str.c_str() << endl;        // convert back to `const char*`

Upvotes: 2

Related Questions