Christoph2 Christoph2 - 29 days ago 7
C++ Question

Python-like string multiplication in C++

As a longtime Python programmer, I really appreciate Python's string multiplication feature, like this:

> print("=" * 5) # =====


Because there is no
*
overload for C++
std::string
s, I devised the following code:

#include <iostream>
#include <string>


std::string operator*(std::string& s, std::string::size_type n)
{
std::string result;

result.resize(s.size() * n);

for (std::string::size_type idx = 0; idx != n; ++idx) {
result += s;
}
return result;
}


int main()
{
std::string x {"X"};

std::cout << x * 5; // XXXXX
}





My question: Could this be done more idiomatic/effective (Or is my code even flawed)?

Answer Source

What about simply using the right constructor for your simple example:

std::cout << std::string('=',5) << std::endl;

For really multiplying strings you should use a simple inline function (and reserve() to avoid multiple re-allocations)

std::string operator*(const std::string& s, size_t n) {
    std::string result;
    result.reserve(s.size()*n);
    for(size_t i = 0; i < n; ++i) {
        result += s;
    }
    return result;
}

and use it

std::cout << (std::string("=+") * 5) << std::endl;

See a Live Demo