w3resource

C++ Exercises: Create a new string without the first and last character of a given string of any length

C++ Basic Algorithm: Exercise-66 with Solution

Write a C++ program to create a new string without the first and last characters of a given string of any length.

Sample Solution:

C++ Code :

#include <iostream> // Including the input/output stream library

using namespace std; // Using the standard namespace

// Function that returns a substring based on the length of input string
string test(string s1)
{
    // Conditional operator to check if the length of the string is less than 2
    return s1.length() < 2 ? " " : s1.substr(1, s1.length() - 2); // Return a substring starting from index 1 to the length-2 of the string
}

// Main function
int main() 
{
    cout << test("Hello") << endl;  // Output the result of test function with "Hello"
    cout << test("JS") << endl;     // Output the result of test function with "JS"
    return 0;    // Return statement indicating successful termination of the program
}

Sample Output:

ell

Visual Presentation:

C++ Basic Algorithm Exercises: Create a new string without the first and last character of a given string of any length.

Flowchart:

Flowchart: Create a new string without the first and last character of a given string of any length.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to move the first two characters to the end of a given string of length at least two.
Next: Write a C++ program to create a new string using the two middle characters of a given string of even length (at least 2).

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.