Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Create a new string which is n copies of the first 3 characters of a given string

C++ Basic Algorithm: Exercise-25 with Solution

Write a C++ program to create a new string which is n (non-negative integer) copies of 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.

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;

string test(string s, int n)
        {
            string result = " ";
            int frontOfString = 3;

            if (frontOfString > s.length())
                frontOfString = s.length();

            string front = s.substr(0, frontOfString);

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

Sample Output:

PytPyt
PytPytPyt
JSJSJS

Pictorial Presentation:

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

Flowchart:

Flowchart: Create a new string which is n copies of the the first 3 characters of a given string.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to create a new string which is n (non-negative integer) copies of a given string.
Next: Write a C++ program to count the string "aa" in a given string and assume "aaa" contains two "aa".

What is the difficulty level of this exercise?