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 character from a given string and the last character from another given string

C++ Basic Algorithm: Exercise-72 with Solution

Write a C++ program to create a new string taking the first character from a given string and the last character from another given string. If the length of any given string is 0, use '#' as its missing character.

Sample Solution:

C++ Code :

#include <iostream>

using namespace std;

string test(string s1, string s2)
        {
            string lastChars = "";

            if (s1.length() > 0)
            {
                lastChars += s1.substr(0, 1);
            }
            else
            {
                lastChars += "#";
            }

            if (s2.length() > 0)
            {
                lastChars += s2.substr(s2.length() - 1);
            }
            else
            {
                lastChars += "#";
            }

            return lastChars;
        }
        
int main() 
 {
  cout << test("Hello", "Hi") << endl;  
  cout << test("Python", "PHP") << endl; 
  cout << test("JS", "JS") << endl; 
  cout << test("Csharp", "") << endl;   
  return 0;    
}

Sample Output:

Hi
PP
JS
C#

Pictorial Presentation:

C++ Basic Algorithm Exercises: Create a new string taking the first character from a given string and the last character from another given string.

Flowchart:

Flowchart: Create a new string taking the first character from a given string and the last character from another given string.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to create a new string of length 2, using first two characters of a given string. If the given string length is less than 2 use '#' as missing characters.
Next: Write a C++ program to create a new string from a given string after swapping last two characters.

What is the difficulty level of this exercise?