# "Replace all As with three ***" (C++)

1. Aug 30, 2014

### Jamin2112

During my in-person interview yesterday, the interviewer asked me to write a function that takes a string and replaces all As with three As

Ex. "Abraham"--->"AAAbraaahaaam"

I did it, but it took me a while to get it right using the replace function (http://www.cplusplus.com/reference/string/string/replace/), because the documentation (which I was allowed to use) doesn't say how the string is re-indexed after using the function. I found it difficult to write the function by iterating through it with an iterator.

Anyways, I was wondering whether someone here could show me their most elegant solution, just so I can see what I could've improved on.

2. Aug 30, 2014

### AlephZero

Not tested, but no iterators were harmed in making this function:
Code (Text):

#include <string>
#include <regex>

string tripleA(string s)
{
return  std::regex_replace(s, std::regex("([Aa])"), "$1$1\$1");
}

3. Aug 30, 2014

### Jamin2112

No boost library, please

4. Aug 30, 2014

### AlephZero

Not boost: standard C++11.

You didn't say it had to work with a legacy programming tools

5. Sep 6, 2014

### voko

Old school:

Code (Text):

void tripleA(std::string &s)
{
for (auto i = s.size(); i > 0; --i)
if (tolower(s[i - 1] == 'a')
s.insert(i, 2, s[i - 1]);
}

6. Sep 6, 2014

### D H

Staff Emeritus
C++11 has fallen into the status of "legacy programming tools". As of August 18, 2014, the current standard is C++14.