0

I want to replace substring within a string, For eg: the string is aa0_aa1_bb3_c*a0_a, so I want to replace the substring a0_a with b1_a, but I dont want aa0_a to get replaced. Basically, no alphabet should be present before and after the substring "a0_a" (to be replaced).

Shubham
  • 43
  • 1
  • 5
  • 1
    Possible duplicate of [Replace part of a string with another string](http://stackoverflow.com/questions/3418231/replace-part-of-a-string-with-another-string) – usamazf Apr 02 '16 at 06:31
  • See this link http://www.cplusplus.com/reference/string/string/replace/ – Shiv Apr 02 '16 at 06:43

2 Answers2

3

That's what regexes are good at. It exists in standard library since C++11, if you have an older version, you can also use Boost.

With the standard library version, you could do (ref):

std::string result;
std::regex rx("([^A-Za-Z])a0_a[^A-Za-Z])");
result = std::regex_replace("aa0_aa1_bb3_c*a0_a", rx, "$1b1_a$2");

(beware: untested)

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • Thanks, it's working, only thing is that $1 prints the entire rx substring, whereas we only want the 1st character of that substring – Shubham Apr 02 '16 at 10:53
  • Separating the strings by brackets did this.. ([^A-Za-z])(a0_a).. regex separates this into 2 parts.. so $1 will only take the first part, i.e. [^A-Za-z] – Shubham Apr 02 '16 at 19:17
0

Easy enough to do if you loop through each character. Some pseudocode:

string toReplace = "a0_a";
for (int i = 0; i < myString.length; i++) {
  //filter out strings starting with another alphabetical char
  if (!isAlphabet(myString.charAt(i))) {
    //start the substring one char after the char we have verified to be not alphabetical
    if (substring(myString(i + 1, toReplace.length)).equals(toReplace)) {
      //make the replacement here
    }
  }
}

Note that you will need to check for indexing out of bounds when looking at the substrings.

nhouser9
  • 6,730
  • 3
  • 21
  • 42
  • Yes, that would work for small strings, but I wud be doing this operation many number of times, iterating over each character of a string will be tedious..... – Shubham Apr 02 '16 at 06:58
  • So, every time we can look for the substring, then check for the char at position (index-1), to be an alphabet..... is there any faster way, like till now I was using boost::replace_all, want a similar function that can take into account this condition as well – Shubham Apr 02 '16 at 07:00