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
raja
Published on 09-Aug-2019 12:24:08
Advertisements