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.
To get the underlying data from a
std::stringYou 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 returnedconst 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 theconst char*: