-1

In Python, there is a way to multiply a string, for example, "A" * 3 would return "AAA". However, this syntax doesn't work in C++, it just gives me an error, invalid operands of types 'const char [2]' and 'int' to binary 'operator*'. Is there a way to multiply a string like this in C++?

LogicalX
  • 95
  • 1
  • 10
  • In C++, it is probably better to make a function: `string repeat(string s, size_t n) { string result; result.reserve(s.size() * n); while(n--) result += s; return result; }` – Eljay Jun 21 '20 at 13:50

3 Answers3

2

There is no such operator in C++.

But you can write a function that takes a string and a number as argument, and return the repeated string.

std::string also has a constructor that repeats given character a number of times. This may be useful since you used a string of one character as the example.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

You can overload an operator

std::string operator*(const std::string& s, unsigned n)
{
    ... // your code here
}
john
  • 85,011
  • 4
  • 57
  • 81
0

Not really... Although you can right one yourself. C++ is a very different beast to Python. It's much more low level and It is not as forgiving. C++ deals with "real" memory (as it were). You can't really just say "A" * 3 because before the "A" simply used 1 byte of memory if you have 3 "A"'s you need 3 bytes. and since C++'s main benefit is in it's ability to allow the user to author It's memory use, C++ won't just create 3 extra bytes.

You can implement your own version of Python's "A" * 3 by using the overload operator (although you would have to use a class type like string) C++ provides But I wouldn't really recommend this.

I'd suggest just using a std::vector and append the character as many times as you would like.

Also have a think about what you are trying to really do. C++ is all about performance rather than usability. If you are trying to set multiple bytes to a certain value you can use std::memset

masonCherry
  • 894
  • 6
  • 14
  • 2
    "A" is (at least) two bytes – OznOg Jun 21 '20 at 13:24
  • where are you getting that information from? – masonCherry Jun 21 '20 at 13:33
  • well the compiler error in the op question already stats it, but "A" is a *null terminated* string, thus "A" is { 'A', '\0' }; thus 2 bytes. I say at least because with utf8 or any other non ascii use, a 'A' may be much larger the a byte. – OznOg Jun 21 '20 at 13:36
  • I was talking more about the fact that you have to create more memory. rather than the exact size.. Thanks – masonCherry Jun 21 '20 at 13:40