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.
## 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
= median(1:length(s))
m floor(Int, m):ceil(Int, m)] # median() 返回 Float
s[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)
## Get the Middle Character
#' @title 提取字符串中间的一个或两个字母
<- function(string) {
get_middle <- median(1:nchar(string)) # middle letter index
m |>
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 🎉
function getMiddle(s) {
= s.length;
n return n % 2 == 1 ? s[(n - 1) / 2] : s.substr(n / 2 - 1, 2);
}
.exports = getMiddle; module