w3resource

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


Long+Short+Long String Combination

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.

For more Practice: Solve these Related Problems:

  • Write a C++ program to combine two strings by placing the shorter string between two copies of the longer string.
  • Write a C++ program that reads two strings, determines which is longer, and then constructs a new string in the format long+short+long.
  • Write a C++ program to compare two strings by length and output a concatenated string formed as long string, short string, and long string.
  • Write a C++ program that accepts two inputs and outputs a new string where the longer string frames the shorter one on both sides.

Go to:


PREV : Remove First and Last Characters.
NEXT : Combine Strings Without First Characters.

C++ Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.