[CodeWars] Get the Middle Character

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 0 < str < 1000 (In javascript you may get slightly more than 1000 in some test cases due to an error in the test cases). You do not need to test for this. This is only here to tell you that you do not need to worry about your solution timing out.


The middle character(s) of the word represented as a string.

My Solution

std::string get_middle(std::string input)
    return input.length()%2 == 1 ?
            input.substr((input.length() / 2), 1) : input.substr((input.length()  1/ 22);;

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.

글쓴이: BakJH

Student of Daedeok SW Meister Highschool, in Korea.

답글 남기기

아래 항목을 채우거나 오른쪽 아이콘 중 하나를 클릭하여 로그 인 하세요:

WordPress.com 로고

WordPress.com의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

Google photo

Google의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

Twitter 사진

Twitter의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

Facebook 사진

Facebook의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

%s에 연결하는 중