I recently found the need to replace a std::string
's contents with a substring of itself. The most logical function to call here I think is the following, from http://www.cplusplus.com/reference/string/string/assign/:
substring (2) string& assign (const string& str, size_t subpos, size_t sublen);
Copies the portion of str that begins at the character position subpos and spans sublen characters (or until the end of str, if either str is too short or if sublen is string::npos).str
Another string object, whose value is either copied or moved.subpos
Position of the first character in str that is copied to the object as a substring. If this is greater than str's length, it throws out_of_range. Note: The first character in str is denoted by a value of 0 (not 1).sublen
Length of the substring to be copied (if the string is shorter, as many characters as possible are copied). A value of string::npos indicates all characters until the end of str.
However, I'm not certain if this is permissible, or if it can corrupt the string data. I know that memcpy()
, for example, does not allow (or at least does not guarantee non-corruption in the case of) overwriting an area of memory with (a portion of) itself (see memcpy() vs memmove()). But I don't know if the above method has the same limitation.
More generally, can you please comment if I should have been able to figure out the answer to this question myself? There's nothing in the documentation I linked to that makes it clear to me what the answer to this question is, except perhaps the qualifier "Another" in the description of the str
parameter ("Another string object"), which seems to imply it cannot be the this object, although I don't find that to be unequivocal. Is that a weakness in the documentation?