How could I replace a substring in a string with another substring in C++, what functions could I use?
eg: string test = "abc def abc def"; test.replace("abc", "hij").replace("def", "klm"); //replace occurrence of abc and def with other substring
Algorithm to Replace a substring in a stringInput the full string (s1). Input the substring from the full string (s2). Input the string to be replaced with the substring (s3). Find the substring from the full string and replace the new substring with the old substring (Find s2 from s1 and replace s1 by s3).
Replace(Char, Char)
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.
You need to copy the string into another, not read-only memory buffer and modify it there. Use strncpy() for copying the string, strlen() for detecting string length, malloc() and free() for dynamically allocating a buffer for the new string.
In c++11, you can use std::regex_replace
:
#include <string> #include <regex> std::string test = "abc def abc def"; test = std::regex_replace(test, std::regex("def"), "klm"); // replace 'def' -> 'klm' // test = "abc klm abc klm"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With