I can't double characters inside string with function

前端 未结 3 554
夕颜
夕颜 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 13:03

    The problem is, newString is always empty, it doesn't contain any elements. Access on it like newString[i] and newString[i+1] leads to UB.

    You need to add elements to it, e.g.

    string doubleChar(const string& str) { // apply pass-by-reference to avoid copy
        string newString;
        newString.reserve(str.size() * 2); // reserve the capacity to avoid reallocation
        for(int i =0;i

提交回复
热议问题