w3resource

C++ Exercises: Create a new string of length 2, using first two characters of a given string

C++ Basic Algorithm: Exercise-71 with Solution

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.

Sample Solution:

C++ Code :

#include <iostream>

using namespace std;

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

            return s1;
        }
int main() 
 {
  cout << test("Hello") << endl;  
  cout << test("Python") << endl; 
  cout << test("a") << endl; 
  cout << test("") << endl;   
  return 0;    
}

Sample Output:

He
Py
a#
##

Pictorial Presentation:

C++ Basic Algorithm Exercises: Create a new string of length 2, using first two characters of a given string.

Flowchart:

Flowchart: Create a new string of length 2, using first two characters of a 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 starting at the given index of a given string.
Next: 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.

What is the difficulty level of this exercise?