Find all occurrences of a substring in a string c++: In the previous article, we have discussed about Converting a String to Upper & Lower Case in C++ using STL & Boost Library. Let us learn how to find and Replace all occurrences of a sub string in C++ Program.
Finding and replacing all occurrences of a sub string in C++
Boost replace_all: In this article we will discuss about how we can find and replace all occurrences of a sub string.
We will see 3 different ways to achieve this.
Method-1 : Using STL
// Program :
#include <iostream>
#include <string>
void FindAndReplace(std::string & data, std::string Searching, std::string replaceStr)
{
// Getting the first occurrence
size_t position = data.find(Searching);
// Repeating till end is reached
while( position != std::string::npos)
{
// Replace this occurrence of Sub String
data.replace(position, Searching.size(), replaceStr);
// Get the next occurrence from the current position
position =data.find(Searching, position + replaceStr.size());
}
}
int main()
{
// Original String
std::string data = "BtechGeeks is Good";
std::cout<<data<<std::endl;
// Replacing 'Good' with 'Best'
FindAndReplace(data, "Good", "Best");
std::cout<<data<<std::endl;
return 0;
}
Output : BtechGeeks is Good BtechGeeks is Best
Method-2 : Using Boost::replace_all
// Program :
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
int main()
{
std::string sample = "BtechGeeks is Good";
std::cout<<sample<<std::endl;
// Replacingb all occurrences of 'Good' with 'Best'
// This is case Sensitive Version
boost::replace_all(sample, "Good", "Best");
std::cout<<sample<<std::endl;
}
Output : BtechGeeks is Good BtechGeeks is Best
Method-3 : Using Boost::ireplace_all
// Program :
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
int main()
{
std::string sample = "BtechGeeks is Good";
std::cout<<sample<<std::endl;
// Replacingb all occurrences of 'Good' with 'Best'
// This is case Sensitive Version
boost::ireplace_all(sample, "Good", "Best");
std::cout<<sample<<std::endl;
}
Output : BtechGeeks is Good BtechGeeks is Best