C++ Exercises: Create a new string using first two characters of a given string
C++ Basic Algorithm: Exercise-60 with Solution
Write a C++ program to create a new string using first two characters of a given string. If the string length is less than 2 then return the original string.
Sample Solution:
C++ Code :
#include <iostream>
using namespace std;
string test(string s1)
{
return s1.length() < 2 ? s1 : s1.substr(0, 2);
}
int main()
{
cout << test("Hello") << endl;
cout << test("Hi") << endl;
cout << test("H") << endl;
cout << test(" ") << endl;
return 0;
}
Sample Output:
He Hi H
Pictorial Presentation:
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to create a new string using three copies of the last two character of a given string of length atleast two.
Next: Write a C++ program to create a new string of the first half of a given string of even length.
What is the difficulty level of this exercise?