C++ Exercises: Create a new string using the first and last n characters from a given string of length at least n
C++ Basic Algorithm: Exercise-68 with Solution
Write a C++ program to create a new string using the first and last n characters from a given string of length at least n.
Sample Solution:
C++ Code :
#include <iostream>
using namespace std;
string test(string s1, int n)
{
return s1.substr(0, n) + s1.substr(s1.length() - n);
}
int main()
{
cout << test("Hello", 1) << endl;
cout << test("Python", 2) << endl;
cout << test("on", 1) << endl;
cout << test("o", 1) << endl;
return 0;
}
Sample Output:
Ho Pyon on oo
Pictorial Presentation:

Flowchart:

C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to create a new string using the two middle characters of a given string of even length (at least 2).
Next: Write a C++ program to create a new string of length 2 starting at the given index of a given string.
What is the difficulty level of this exercise?
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework