Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting string into char

Tags:

c++

I know I can do this by str.c_str(), but I do not want a character constant. I want a char so that I can make some modifications.

char* removeDup(char *s)
{


        int len = strlen(s);
        int p,q, idx = -1;
    for(p = 0; p< len; p++)
   {
    char temp = s[p];
    bool flag = true;
    for(q=0;q<p;q++)
    {
        if(s[q] == temp)
        {
            flag = false;
            break;
        }
    }
    if(flag == true)
    {
        s[++idx] = temp;
    }
}
    s[++idx] = '\0';
    return s;
}

if I call this function as below, I get errors;

string s = "abcde";
removeDuplicate(s.c_str());

I need to convert this s into char and not const char.

like image 763
Roger Avatar asked Mar 01 '26 18:03

Roger


1 Answers

To get the underlying data from a std::string You can use:

string::data() or string::c_str(), both return a const char *.

In either case the returned data is const char * because the memory for it is allocated in some read only implementation defined region which an user program is not allowed to modify. Any attempt to modify the returned const char * would result in Undefined Behavior.

So you cannot and should not(through const_cast) modify the returned character string.

The only correct way to achieve this by creating a new char*, allocate it, and copy in the contents from the const char*:

std::string myString = "blabla";
char* myPtr = new char[myString.size() + 1];
myString.copy(myPtr, myString.size());
myPtr[myString.size()] = '\0';
like image 105
Luchian Grigore Avatar answered Mar 03 '26 06:03

Luchian Grigore