Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

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

  1. Aug 30, 2014 #1
    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. jcsd
  3. Aug 30, 2014 #2

    AlephZero

    User Avatar
    Science Advisor
    Homework Helper

    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");
    }
     
     
  4. Aug 30, 2014 #3
    No boost library, please
     
  5. Aug 30, 2014 #4

    AlephZero

    User Avatar
    Science Advisor
    Homework Helper

    Not boost: standard C++11.

    You didn't say it had to work with a legacy programming tools :smile:
     
  6. Sep 6, 2014 #5
    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]);
    }
     
     
  7. Sep 6, 2014 #6

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    C++11 has fallen into the status of "legacy programming tools". As of August 18, 2014, the current standard is C++14.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: "Replace all As with three ***" (C++)
  1. To C or not to C (Replies: 31)

  2. C or C++? (Replies: 8)

  3. Java or C/C ++ (Replies: 5)

Loading...