Thursday, January 1, 2009

How to create replaceAll() (C++) ?

Happy New Year World, this is my first post in 2009. This time I will tell about how to create replaceAll() function. This function are used to replace part of original string that contains old value to new value. The idea just iterate the string you want to replace and take the substring from each index then compare to the value you want to replace.

You can see the fullcode below :

#include "iostream"
#include "string"
using namespace std;

string replaceAll(string text,string from,string to) {
string result = "";
int i = 0;
while(i < text.size())
{
if(i+from.size() <= text.size() && text.substr(i,from.size())==from )
{
result += to;
i += from.size();
}
else
{
result.push_back(text[i]);
i++;
}
}
return result;
}

int main() {
string a = "C++ is easy";
cout << a << endl;
a = replaceAll(a,"C++ is","C++ and Java are");
cout << a << endl;
return 0;
}


2 comments:

  1. Sorry be4, I'm a new bie in java
    Isn't there any build-in function in java to do the same job as yours?

    ReplyDelete
  2. Yes, you can use replaceAll() method in String class.

    ReplyDelete