Description

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.

Examples

Kata.getMiddle("test") should return "es"
Kata.getMiddle("testing") should return "t"
Kata.getMiddle("middle") should return "dd"
Kata.getMiddle("A") should return "A"

Input

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.

Output

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

Solutions

Julia

## Get-the-Middle-Character.jl

using Statistics, Test


"""
return middle character(s) of a string
"""
#> "return middle character(s) of a string\n"
function getmiddle(s::String)::String
    m = median(1:length(s))
    s[floor(Int, m):ceil(Int, m)] # median() 返回 Float
end
#> getmiddle (generic function with 1 method)


@testset "Sample tests" begin
    @test getmiddle("test") == "es"
    @test getmiddle("testing") == "t"
end
#> Test Summary: | Pass  Total
#> Sample tests  |    2      2
#> Test.DefaultTestSet("Sample tests", Any[], 2, false, false)

R

## Get the Middle Character

#' @title 提取字符串中间的一个或两个字母
get_middle <- function(string) {
    m <- median(1:nchar(string))  # middle letter index
    string |>
        str_sub(floor(m), ceiling(m))
}

library(testthat)
test_that("Sample Tests", {
    expect_equal(get_middle("test"), "es")
    expect_equal(get_middle("testing"), "t")
    expect_equal(get_middle("middle"), "dd")
    expect_equal(get_middle("A"), "A")
    expect_equal(get_middle("of"), "of")
})
#> Test passed 🎉

JavaScript

function getMiddle(s) {
  n = s.length;
  return n % 2 == 1 ? s[(n - 1) / 2] : s.substr(n / 2 - 1, 2);
}

module.exports = getMiddle;