C++ String replace() – Replace Text in a String (Examples)
This Snippet is coded by a user inOnline cpp Compiler. You can see and run this code too.
زبان: C++
The std::string::replace() function modifies a string in place by replacing a specified range with new content. Its most common overload takes a starting position, a count of characters to remove, and the replacement text: str.replace(pos, count, new_text). For example, text.replace(2, 4, "enjoy") removes four characters starting at index 2 and inserts "enjoy" at that position. The function returns a reference to the modified string, so it can be chained or used directly.
Inputs are the zero-based starting index, the number of characters to erase, and the replacement string. The output is the original string object with the range substituted. If pos is beyond the string length, std::out_of_range is thrown. If count exceeds the remaining characters, only the available characters are replaced.
To replace every occurrence of a substring, combine find() with replace() in a loop. After each replacement, advance the search position by the replacement length to avoid reprocessing inserted text.
Time complexity for a single replacement is O(n + m) in the worst case, where n is the string length and m is the replacement length, because trailing characters may be shifted. Replacing k occurrences can cost O(k × n). Use reserve() and build a new string for heavy bulk edits.