How to repeat a string a variable number of times in C++?

how to repeat a string n times in c
how to repeat a string n times in c++
c++ repeat n times
repeated string hackerrank solution in c++
how to repeat a string n times in java
concatenate string multiple times
how to print a number n times in c
how to print a character n times in c

I want to insert 'n' spaces (or any string) at the beginning of a string in C++. Is there any direct way to do this using either std::strings or char* strings?

E.g. in Python you could simply do

>>> "." * 5 + "lolcat"
'.....lolcat'

In the particular case of repeating a single character, you can use std::string(size_type count, CharT ch):

std::string(5, '.') + "lolcat"

NB. This can't be used to repeat multi-character strings.

Repeat a string, using namespace std;. // Function which return string by concatenating it. string repeat(string s, int� Repeat substrings of the given String required number of times. Given a string str, the task is to repeat every substring of the string X number of times where X is the number composed of the consecutive digits present just after the substring in the original string. For example, if str = “g1e2ks1” then the resultant string will be “geeks”.

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, '.')

This is a contrived example of how you might use an ostringstream to repeat a string n times:

#include <sstream>

std::string repeat(int n) {
    std::ostringstream os;
    for(int i = 0; i < n; i++)
        os << "repeat";
    return os.str();
}

Depending on the implementation, this may be slightly more efficient than simply concatenating the string n times.

C++ program to concatenate a string given number of times , Question. I want to insert 'n' spaces (or any string) at the beginning of a string in C ++. Is there any direct way to do this using either std::strings or char* strings? Take a string and repeat it some number of times. Example: repeat ("ha", 5) => "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char ("*", 5) => "*****").

Use one of the forms of string::insert:

std::string str("lolcat");
str.insert(0, 5, '.');

This will insert "....." (five dots) at the start of the string (position 0).

How to repeat a string a variable number of times in C++?, Number of time the input string should be repeated. multiplier has to be Here is a simple one liner to repeat a string multiple times with a separator: <?php To create a string by repeating a character a number of times: Type string str where str is the name of the variable to hold the string. Type = new string ('A',5), where 'A' is any character (characters are represented in single quotes), and 5 is the number of times you wish to repeat that character.

I know this is an old question, but I was looking to do the same thing and have found what I think is a simpler solution. It appears that cout has this function built in with cout.fill(), see the link for a 'full' explanation

http://www.java-samples.com/showtutorial.php?tutorialid=458

cout.width(11);
cout.fill('.');
cout << "lolcat" << endl;

outputs

.....lolcat

str_repeat - Manual, For example - String s = “Hello”; You want to repeat this string 10 times, i.e n=10. Now using for loop, for(int i=1 ; i<=n ; i++) { System.out.println(s); // This line will print this string Couldn't I just assign the string variable to a different string? C# doesn’t have built-in function to repeat a string. There are different version for string.Repeat () available in internet and it’s up to reader to find out which version works better. Here is the list of most popular implementations I found across the web. I list my findings here with the results of simple performance test.

For the purposes of the example provided by the OP std::string's ctor is sufficient: std::string(5, '.'). However, if anybody is looking for a function to repeat std::string multiple times:

std::string repeat(const std::string& input, unsigned num)
{
    std::string ret;
    ret.reserve(input.size() * num);
    while (num--)
        ret += input;
    return ret;
}

How to repeat a string n number of times in Java programming, to your code. We'll also take a first look at String methods and solve some interesting problems. Using a while statement, we can repeat the same code multiple times: System.out.print("Roman alphabet: "); for (char c = 'A'; c <= 'Z'; c ++)� Can be done in one loop using variable field width formatting for both the spaces and the number of '#' shown from a predefined array containing 24 '#' (specified as maximum needed) characters. Quick Navigation C Programming Top

Loops and Strings | Think Java, An integer between 0 and +Infinity , indicating the number of times to repeat the string. Return value. A new string containing the specified number� In C++, there is a way to initialize a string with a value. It can be used to print a character as many times as we want. While declaring a string, it can be initialized by using the feature provided by c++. It takes 2 arguments. First is the number of times we want to print a particular character and the other is the character itself.

String.prototype.repeat(), If you are only interested in the result of repeating the string/char a number of times without using the * operator , than a function with some loop� 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'.By this you can redefine * operator's functionality for a custom made string or character class.This is known as C++ "object oriented programming".

Can you print more than one char in C by using "x" * 5 like you can , Repeat the character strings in a character vector a given number of times (i.e., concatenate the respective numbers of copies of the strings). 2) strrep(c("A", "B" , "C"), 1 : 3) ## Create vectors with the given numbers of spaces: strrep(" ", 1 : 5)� To repeat the vector c (0, 0, 7) three times, use this code: > rep (c (0, 0, 7), times = 3) [1] 0 0 7 0 0 7 0 0 7. You also can repeat every value by specifying the argument each, like this: > rep (c (2, 4, 2), each = 3) [1] 2 2 2 4 4 4 2 2 2. R has a little trick up its sleeve.

Comments
  • Someone provide an answer using QString?
  • The OP asked for repeating a string, not a character.
  • The OP asked for repeating a string, not a character.
  • @Brent The OP asked for both - "'n' spaces (or any string)", and then goes on to demonstrate their intent with a single period as the string. English is not many people's first language so you sometimes need to guess their exact requirements and when analysed, the question is really asking how to do this with a single character. I'm sorry you found my answer unhelpful enough you needed to down vote it.
  • only dots: change last line to... cout << "" << endl;
  • Your implementation does not 'minimize copying'. Mind that the += within your for loop internally also has a loop of some sort which does str.size() iterations. str.size() grows in each outer loop iteration, so after each outer iteration the inner loop has to do more iterations. Your and the naive 'copy n times' implementation in total both copy n * period characters. Your implementation does only one memory allocation because of the initial reserve. I guess you profiled your implementation with a rather small str and a big n, but not also with big str and a small n.
  • @FlorianKaufmann Not sure why you've chosen to attack my answer. But by "minimise copying" I mean 'copying operations'. The idea being that copying a small number of big blocks is more efficient (for a variety of reasons) than copying a large number of small blocks. I potentially avoid an additional allocation on the input string over the naive method.
  • It was a comment stating that I don't believe your claim that your solution is much better in terms of efficiency than the naive solution. In my measurements, compared to the naive solution, your code is faster with small strings and many repetitions, but slower with long strings and few repetitions. Could you provide links explaining in more detail the variety of reasons why copying a few big blocks has a higher performance than copying many small blocks? I can think of branch prediction. Regarding CPU cache I am unsure which variant is preferred.
  • @FlorianKaufmann I see no significant difference for big str and small n between the two approaches. I believe this is more to do with overall pipeline than branch prediction per-se, there's also data alignment issues to consider. You should ask a new question for the particulars of why this is more processor/memory friendly, I'm sure it would gain a lot of interest, and receive a better answer than I can give here.
  • @FlorianKaufmann: On x86, rep movsb is one of the most efficient ways to copy, at least for medium to large copies. Its micro-coded implementation has some near-constant startup overhead (on both AMD and Intel), e.g. on Sandybridge, ~15 to 40 cycles, plus 4 cycles per 64B cache line (best case). For small copies, an SSE loop is best because it doesn't have the startup overhead. But then it's subject to branch mispredicts.
  • writing a stream manipulator is a very complicated way of doing something very simple!
  • C++ is a very complicated way of doing something very simple.
  • What on earth does "ITNOA" mean? Can't find any reference to it online.