w3resource

C++ Exercises: Create a new string which is n copies of a given string

C++ Basic Algorithm: Exercise-24 with Solution

Write a C++ program to create a new string which is n (non-negative integer) copies of a given string.

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;

string test(string s, int n)
        {
            string result = "";
            for (int i = 0; i < n; i++)
            {
                result += s;
            }
            return result;
        }
        
int main() 
 {
  cout << test("JS", 2) << endl;  
  cout << test("JS", 3) << endl;  
  cout << test("JS", 1) << endl;  
  return 0;    
}

Sample Output:

JSJS
JSJSJS
JS

Pictorial Presentation:

C++ Basic Algorithm Exercises: Create a new string which is n copies of a given string.

Flowchart:

Flowchart: Create a new string which is n copies of a given string.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to check if two given non-negative integers have the same last digit.
Next: Write a C++ program to create a new string which is n (non-negative integer) copies of the the first 3 characters of a given string. If the length of the given string is less than 3 then return n copies of the string.

What is the difficulty level of this exercise?