C++ Exercises: Create a new string of the first half of a given string of even length
C++ Basic Algorithm: Exercise-61 with Solution
First Half of Even-Length String
Write a C++ program to create the string of the first half of a given string of even length.
Sample Solution:
C++ Code :
#include <iostream> // Include the input/output stream library
using namespace std; // Use the standard namespace
// Function definition to return the first half of the input string
string test(string s1) // Function named 'test' accepting a string parameter 's1'
{
return s1.substr(0, s1.length() / 2); // Return a substring from index 0 to half the length of the input string 's1'
}
// Main function - entry point of the program
int main()
{
cout << test("Hello") << endl;
cout << test("Hi") << endl;
return 0; // Indicate successful completion of the program
}
Sample Output:
He H
Visual Presentation:
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to create a new string using first two characters of a given string. If the string length is less than 2 then return the original string.
Next:Write a C++ program to create a new string without the first and last character of a given string of length atleast two.
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-61.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics