intrigued_66
intrigued_66

Reputation: 17240

Modifying char array from string

I'd like to initialise a string and then modify the resultant char array. I did:

std::string str = "hello world";
const char* cstr = str.c_str();

// Modify contents of cstr

However, because cstr is const, I cannot modify the elements. If I remove const, I cannot use c_str().

What is the best way to achieve this?

Upvotes: 0

Views: 122

Answers (2)

Hatted Rooster
Hatted Rooster

Reputation: 36463

The best and most straight forward way to do this is to just directly modify the std::string using its own operator[]:

str[0] = 'G'; // "Gello world"

If you truly need to copy the C-string, for whatever reason, then you have to create a new buffer, eg:

char* buffer = new char[str.length() + 1];
strcpy(buffer, str.c_str());
delete[] buffer;

The obvious flaw here is dynamic allocation. Just stick with modifying the std::string directly, it's what the class is written for, to make your life easier.

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

Just modify str using the std::string member functions.

These functions include operator[].

Since C++11 (and assuming a compliant implementation), &str[0] is the pointer that you want.

Upvotes: 4

Related Questions