I can't double characters inside string with function

前端 未结 3 617
夕颜
夕颜 2021-01-23 12:18

I am trying to create a simple function that double the characters inside of a string and outputs the new string. Ex. "hello world" would become "hheelloo wwoorrl

3条回答
  •  忘掉有多难
    2021-01-23 12:45

    Altough the solution by songyuanyao is nice, I think more C++ functions can be used...

    #include 
    #include 
    
    // use string view, so a character array is also accepted
    std::string DoubleChar(std::string_view const &str) noexcept {
        std::string newString;
        newString.reserve(str.size() * 2);
        for (auto character : str) { // use range based loop
            newString.append(2, character); // append the character twice
        }
        return newString;
    }
    
    #include 
    
    int main() {
        std::string const str = "Hello world";
    
        std::cout << DoubleChar(str) << '\n';
    }
    

提交回复
热议问题