w3resource

C++ Exercises: Create a new string of the first half of a given string of even length

C++ Basic Algorithm: Exercise-61 with Solution

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:

C++ Basic Algorithm Exercises: Create a new string of the first half of a given string of even length.

Flowchart:

Flowchart: Create a new string of the first half of a given string of even length.

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?



Follow us on Facebook and Twitter for latest update.