Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore (’_’).
* 'abc' => ['ab', 'c_']
* 'abcdef' => ['ab', 'cd', 'ef']
library(tidyverse)
library(magrittr)
<- function(string) {
solution %>%
string str_c("_") %>%
str_extract_all(".{2}") %>%
extract2(1)
}
library(testthat)
test_that("Sample Tests", {
expect_equal(solution("abc"), c("ab", "c_"))
expect_equal(solution("abcd"), c("ab", "cd"))
})
#> Test passed 🥳
function solution(str) {
// 解法一:遍历字符的 index
// const n = str.length;
// let array = [];
// if (n % 2 === 1) {
// str += '_';
// }
// for (let i = 0; i < n / 2; i++) {
// array.push(str.slice(2 * i, 2 * i + 2));
// }
// return array;
// 解法二:string.match() 正则匹配
// str 为 '' 时,匹配失败返回 null,对应的布尔值为 flase
// 短路逻辑,返回第一个布尔值为 true 的初始值,即[]
return (str + "_").match(/.{2}/g) || [];
// 等价于
// if (str === '') {
// return [];
// } else {
// return (str + "_").match(/.{2}/g);
// }
}
.exports = solution; module