#include <iostream> #include <string> using namespace std; string middle(string str) { int length = str.length(); if(length % 2 == 0) { return str.substr(length / 2 -1, 2); } else { return str.substr(length/2, 2); } } int main() { string word, result; cout << "Enter the word: "; cin >> word; result = middle(word); cout << result << "\n"; return 0; }
Question
#include <iostream> #include <string> using namespace std;
string middle(string str)
{
int length = str.length();
if(length % 2 == 0)
{
return str.substr(length / 2 -1, 2);
}
else
{
return str.substr(length/2, 2);
}
}
int main() { string word, result; cout << "Enter the word: "; cin >> word; result = middle(word);
cout << result << "\n";
return 0;
}
Solution
This is a C++ program that takes a string input from the user and returns the middle character(s) of the string. If the length of the string is even, it returns the middle two characters. If the length of the string is odd, it returns the middle character and the character after it.
Here's a step-by-step explanation:
-
The
middlefunction is defined. It takes a string as an argument and returns a string. -
The length of the string is calculated using the
length()function and stored in thelengthvariable. -
An
ifstatement checks if the length of the string is even by using the modulus operator%. If the length is even, thesubstrfunction is used to return the middle two characters of the string. Thesubstrfunction takes two arguments: the starting index and the number of characters to include in the substring. In this case, the starting index islength / 2 - 1(the index of the first middle character) and the number of characters is2. -
If the length of the string is odd, the
elseblock is executed. Thesubstrfunction is used to return the middle character and the character after it. The starting index islength / 2. -
In the
mainfunction, the user is prompted to enter a word. This word is stored in thewordvariable. -
The
middlefunction is called withwordas the argument, and the result is stored in theresultvariable. -
The result is printed to the console.
-
The program returns
0and ends.
Similar Questions
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.