w3resource

C++ Exercises: Create a new string from two given string one is shorter and another is longer

C++ Basic Algorithm: Exercise-63 with Solution

Write a C++ program to create a new string from two given strings, one of which is shorter and the other is larger. The format of the updated string will be long string + short string + long string.

Sample Solution:

C++ Code :

#include <iostream> // Including the input/output stream library

using namespace std; // Using the standard namespace

// Function that concatenates strings based on their lengths
string test(string s1, string s2)
{
    // Conditional operator to determine which string concatenation to perform
    return s1.length() < s2.length() ? s2 + s1 + s2 : s1 + s2 + s1;
}

// Main function
int main() 
{
    cout << test("Hello", "Hi") << endl;  // Output the result of test function with "Hello" and "Hi"
    cout << test("JS", "Python") << endl; // Output the result of test function with "JS" and "Python"
    return 0;    // Return statement indicating successful termination of the program
}

Sample Output:

HelloHiHello
PythonJSPython

Visual Presentation:

C++ Basic Algorithm Exercises: Create a new string from two given string one is shorter and another is longer.

Flowchart:

Flowchart: Create a new string from two given string one is shorter and another is longer.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to create a new string without the first and last character of a given string of length atleast two.
Next: Write a C++ program to concat two given string of length atleast 1, after removing their first character.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.