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 taking the first 3 characters of a given string and return the string with the 3 characters added at both the front and back

C++ Basic Algorithm: Exercise-11 with Solution

Write a C++ program to create a new string taking the first 3 characters of a given string and return the string with the 3 characters added at both the front and back. If the given string length is less than 3, use whatever characters are there.

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;

string  test(string str)
        {
             if (str.length() < 3)
            {
                return str + str + str;
            }
            else
            {
                string front = str.substr(0, 3);
                return front + str + front;
            }
        }
        
int main() 
 {
  cout << test("Python") << endl;  
  cout << test("JS") << endl;  
  cout << test("Code") << endl;  
  return 0;    
}

Sample Output:

PytPythonPyt
JSJSJS
CodCodeCod

Pictorial Presentation:

C++ Basic Algorithm Exercises: Create a new string taking the first 3 characters of a given string and return the string with the 3 characters added at both the front and back.

Flowchart:

Flowchart: Create a new string taking the first 3 characters of a given string and return the string with the 3 characters added at both the front and back.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to check if a given positive number is a multiple of 3 or a multiple of 7.
Next: Write a C++ program to check if a given string starts with 'C#' or not.

What is the difficulty level of this exercise?