C++ String Interview Question

后端 未结 7 1213
悲哀的现实
悲哀的现实 2021-02-13 18:22

I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised

7条回答
  •  深忆病人
    2021-02-13 19:12

    Memcpy is a cheat?

    #include 
    #include 
    #include 
    
    std::string first_last_n(int n, const std::string& s)
    {
      if (s.size() < n)
          return "";
    
        char str[n*2];
        memcpy(str, s.data(), n);
        memcpy(str+n, s.data() + s.size()-n, n);
    
        return (const char *)str;
    }
    
    int main()
    {
        std::cout << first_last_n(2, "123454321") << std::endl;
    }
    

    EDIT So I removed the other one. This is not a cheat.

提交回复
热议问题