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



Follow us on Facebook and Twitter for latest update.

C++ Programming: Tips of the Day

What is the "-->" operator in C/C++?

--> is not an operator. It is in fact two separate operators, -- and >.

The conditional's code decrements x, while returning x's original (not decremented) value, and then compares the original value with 0 using the > operator.

To better understand, the statement could be written as follows:

while( (x--) > 0 )

Ref : https://bit.ly/3kOTBby





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook