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

Add First 3 Characters to Front and Back

Write a C++ program to create a string taking the first 3 characters of a given string. Then, return the string with the 3 characters added to 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;

// Function to modify a string based on its length
string test(string str)
{
    if (str.length() < 3) // Check if the length of the string is less than 3
    {
        return str + str + str; // Return the concatenated string three times if its length is less than 3
    }
    else
    {
        string front = str.substr(0, 3); // Extract the first three characters of the string
        return front + str + front; // Concatenate the first three characters, the original string, and again the first three characters
    }
}

// Main function
int main() 
{
    cout << test("Python") << endl;  // Output the result of test function with string "Python"
    cout << test("JS") << endl;      // Output the result of test function with string "JS"
    cout << test("Code") << endl;    // Output the result of test function with string "Code"
    return 0;    // Return 0 to indicate successful execution of the program
}

Sample Output:

PytPythonPyt
JSJSJS
CodCodeCod

Visual 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?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/cpp-exercises/basic-algorithm/cpp-basic-algorithm-exercise-11.php