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 of length 2 starting at the given index of a given string

C++ Basic Algorithm: Exercise-69 with Solution

Write a C++ program to create a new string of length 2 starting at the given index of a given string.

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;

string test(string s1, int index)
        {
            return index + 2 <= s1.length() ? s1.substr(index, 2) : s1.substr(0, 2);
        }
         
int main() 
 {
  cout << test("Hello", 1) << endl;  
  cout << test("Python", 2) << endl; 
  cout << test("on", 1) << endl; 
  return 0;    
}

Sample Output:

el
th
on

Pictorial Presentation:

C++ Basic Algorithm Exercises: Create a new string of length 2 starting at the given index of a given string.

Flowchart:

Flowchart: Create a new string of length 2 starting at the given index of a given string.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: 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.
Next: Write a C++ program to create a new string taking 3 characters from the middle of a given string at least 3.

What is the difficulty level of this exercise?