You are going to be given a word. Your job is to return the middle character of the word. If the word’s length is odd, return the middle character. If the word’s length is even, return the middle 2 characters.
Kata.getMiddle("test") should return "es" Kata.getMiddle("testing") should return "t" Kata.getMiddle("middle") should return "dd" Kata.getMiddle("A") should return "A"
A word (string) of length
The middle character(s) of the word represented as a string.
std::string get_middle(std::string input)
return input.length()%2 == 1 ?
input.substr((input.length() / 2), 1) : input.substr((input.length() – 1) / 2, 2);;
The cases are two. One is the length of input is odd, the other is even.
If the length is odd, returns input[ length/2 ]. If not, returns input[ (length/2) -1 ] and input [ length/2 ]. I used substr() method to realize it.