Andiana Andiana - 10 months ago 61
C++ Question

Init and use C++ std::string as array of char

I want to use a std::string for dynamic string handling. The data is append and append to a string, sometime I wan't to set the value for the character at index i. I don't know how many character will be added to string. Something like dynamic collection in .NET.
When I allocate a std::string in C++

std::string s;

and try to set element at index i for it:

s[0] = 'a';

It will through an error related to memory.
A stupid way is init it with exist data and replace them later:

std::string s = generate1000chars();
s[2] = 'c';

Is there a way to init a string that allow manipulate character at index i, like a char array?

Answer Source

Maybe you can try a wrapper function like

std::string& SetChar(std::string& str, char ch, size_t index)
    if (str.length() <= index)
        str.resize(index + 1);
    str[index] = ch;
    return str;

So that the string can auto extend if needed. (Modified to a better signature)