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
String Without First and Last Characters
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:
Flowchart:
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?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/cpp-exercises/basic-algorithm/cpp-basic-algorithm-exercise-66.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics