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 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:

C++ Basic Algorithm Exercises: Create a new string using the first and last n characters from a given string of length at least n.

Flowchart:

Flowchart: Create a new string using the first and last n characters from a given string of length at least n.

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?