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

  • Context: C/C++ 
  • Thread starter Thread starter Jamin2112
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
5 replies · 2K views
Jamin2112
Messages
973
Reaction score
12
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.
 
Physics news on Phys.org
Not tested, but no iterators were harmed in making this function:
Code:
#include <string>
#include <regex>

string tripleA(string s) 
{
return  std::regex_replace(s, std::regex("([Aa])"), "$1$1$1");
}
 
AlephZero said:
Not tested, but no iterators were harmed in making this function:
Code:
#include <string>
#include <regex>

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

No boost library, please
 
Old school:

Code:
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]);
}