Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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::strings, 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)?

like image 461
Christoph2 Avatar asked Sep 23 '17 11:09

Christoph2


People also ask

Can I multiply strings in C?

you cannot multiply a string.

Can we multiply char in C?

No, you can't do this in 'C' as far as I think.In python multiplication of a string by a number is defined as 'repetition' of the string that number of times. One way you can do this in 'C++'(a superset of 'C' language) is through 'operator overloading'.

Can I multiply a string in Python?

Multiplication. You can do some funny things with multiplication and strings. When you multiply a string by an integer, Python returns a new string. This new string is the original string, repeated X number of times (where X is the value of the integer).

Can we multiply string variable?

No, you can't. However you can use this function to repeat a character.


1 Answers

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

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

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

like image 178
user0042 Avatar answered Sep 27 '22 20:09

user0042