In this article we will discuss how to replace all occurrences of a sub string with new string in C++.
For example, we have a string i.e.
“Boost Library is simple C++ Library”
And we want replace all occurrences of ‘Lib’ with XXX. Let’s see the different methods to do it,
Find & Replace all sub strings – using STL
#include <iostream> #include <string> void findAndReplaceAll(std::string & data, std::string toSearch, std::string replaceStr) { // Get the first occurrence size_t pos = data.find(toSearch); // Repeat till end is reached while( pos != std::string::npos) { // Replace this occurrence of Sub String data.replace(pos, toSearch.size(), replaceStr); // Get the next occurrence from the current position pos =data.find(toSearch, pos + replaceStr.size()); } } int main() { std::string data = "Boost Library is simple C++ Library"; std::cout<<data<<std::endl; findAndReplaceAll(data, "Lib", "XXX"); std::cout<<data<<std::endl; return 0; }
Output:
Boost Library is simple C++ Library Boost XXXrary is simple C++ XXXrary
Find & Replace all sub strings – using Boost::replace_all
#include <iostream> #include <string> #include <boost/algorithm/string.hpp> int main() { std::string data = "Boost Library is simple C++ Library"; std::cout<<data<<std::endl; // Replace all occurrences of 'LIB' with 'XXX' // Case Sensitive Version boost::replace_all(data, "Lib", "XXX"); std::cout<<data<<std::endl; }
Output:
Pointers in C/C++ [Full Course]
Frequently Asked:
Boost Library is simple C++ Library Boost XXXrary is simple C++ XXXrary
Find & Replace all Case Insensitive Sub Strings using Boost::ireplace_all
#include <iostream> #include <string> #include <boost/algorithm/string.hpp> int main() { std::string data = "Boost Library is simple C++ Library"; std::cout<<data<<std::endl; // Replace all occurrences of 'LIB' with 'XXX' // Case Insensitive Version boost::ireplace_all(data, "LIB", "XXX"); std::cout<<data<<std::endl; }
Output:
Boost Library is simple C++ Library Boost XXXrary is simple C++ XXXrary
thanks for sharing tips. first post i read!
i hope can read all your tip in the next week ^^.
1st.
//with erase & insert
#include
using namespace std;
void replace_(string& str, string toSearch, string replaceWith)
{
int pos = str.find(toSearch);
while (pos != string::npos)
{
str.erase(pos, toSearch.length());
str.insert(pos, replaceWith);
pos = str.find(toSearch, pos + replaceWith.length());
}
}
int main()
{
string str = “Boost Library is simple C++ Library”;
replace_(str, “Lib”, “XXXY”);
cout<<str<<endl;
return 0;
}