Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you multiply a QString, so it repeats itself n times?

Tags:

qt

qstring

I need my string to repeat n amount of times, something like this:

QString s("Dog");
qDebug() << s * 3;
"DogDogDog"

I know you can do it with single char's, but I can't figure out how to do it with strings, without resorting to creating a for loop like this:

https://paste.fedoraproject.org/300131/94336814/

Any shortcuts?

like image 397
Anon Avatar asked Dec 12 '15 18:12

Anon


People also ask

How do you repeat a character in C++?

There's no direct idiomatic way to repeat strings in C++ equivalent to the * operator in Python or the x operator in Perl. If you're repeating a single character, the two-argument constructor (as suggested by previous answers) works well: std::string(5, '.

What method or operator can be used to repeat a string?

repeat() The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.

Can I multiply strings?

Multiply Strings Using String(). The first method to multiply a string is to use the replace() function of the String class. This replace method accepts two arguments; the first one is the target, which is the string that we want to be replaced, and the second one is the replacement string.

How do you repeat a character in Javascript?

The repeat() method returns a string that has been repeated a desired number of times. If the count parameter is not provided or is a value of 0, the repeat() method will return an empty string. If the count parameter is a negative value, the repeat() method will return RangeError.


1 Answers

QString simply has not such an operator (see the documentation), so you can't use operator* to do that.

Anyway, QString has an interesting method called repeated.
I cite the documentation, that is quite exhaustive:

Returns a copy of this string repeated the specified number of times.

If times is less than 1, an empty string is returned.

It follows an example, once more from the official documentation:

QString str("ab");
str.repeated(4); // returns "abababab"

I guess this solves your problem and it seems to be the more concise solution available.

like image 95
skypjack Avatar answered Sep 27 '22 15:09

skypjack