E5.6Write a function
string middle(string str)
that returns a string containing the middle character in str if the length of str is odd, or the two middle characters if the length is even. For example, middle("middle") returns "dd".
Please explain in detail. Use conditions if possible.
#include <iostream> #include <string> using namespace std; string middle(string s) { if (s.size() % 2 == 0) { // if string is of even length return s.substr((s.size()-1)/2, 2); // return middle 2 characters } else { // if string is of even odd length return s.substr(s.size()/2, 1); // then return the middle single character } } int main() { cout << middle("middle") << endl; cout << middle("abcde") << endl; return 0; }
Get Answers For Free
Most questions answered within 1 hours.