Concatenate a string given number of times in C++ programming


A program to concatenate a string a given number of times will run the string concatenate method n number of times based on the value of n.

The result would be string repeated a number of times.

Example

given string: “ I love Tutorials point”
n = 5

Output

I love Tutorials pointI love Tutorials pointI love Tutorials pointI love Tutorials point
I love Tutorials point

After seeing the output, it is clear that what the function will do.

Example

#include <iostream>
#include <string>
using namespace std;
string repeat(string s, int n) {
   string s1 = s;
   for (int i=1; i<n;i++)
      s += s1; // Concatinating strings
   return s;
}
// Driver code
int main() {
   string s = "I love tutorials point";
   int n = 4;
   string s1 = s;
   for (int i=1; i<n;i++)
   s += s1;
   cout << s << endl;;
   return 0;
}

Output

I love tutorials pointI love tutorials pointI love tutorials pointI love tutorials point

Updated on: 09-Aug-2019

537 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements