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
Altough the solution by songyuanyao is nice, I think more C++ functions can be used...
#include <string>
#include <string_view>
// 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 <iostream>
int main() {
std::string const str = "Hello world";
std::cout << DoubleChar(str) << '\n';
}
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<str.size();++i){
newString += str[i];
newString += str[i];
// or use push_back or append
}
return newString;
}
using namespace std;
string doubleChar(string str) {
string newString(str.size() * 2, '\0');
for(int i =0;i<str.size();++i){
newString[2*i] = str[i];
newString[2*i+1] = str[i];
}
return newString;
}
The length of result should be set twice of the input. And index should be multiplied by 2.