7. Split Strings

124 阅读1分钟

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 ('_').

Example

* 'abc' =>  ['ab', 'c_']
* 'abcdef' => ['ab', 'cd', 'ef']
我的解法:
function solution(str){
    if (!str) return []
    var arr = str.split('')
    var teamArr = []
    for (let i = 0; i < arr.length; i++) {
      teamArr.push(arr[i] + `${arr[i + 1] || '_'}`);
      i+=1
    }
    return teamArr
}
unlock solution

参考一:
function solution(s){
   return (s+"_").match(/.{2}/g)||[]
}

🌟关键点:
1. /./g匹配除换行符外的任何单个字符
2. String.prototype.match()方法检索返回一个字符串匹配正则表达式的结果


参考二:
function solution(str){
  var i = 0;
  var result = new Array();
  if (str.length % 2 !== 0) {
     str = str + '_';
  }

  while (i < str.length) {
      result.push(str[i] + str[i+1]);
      i += 2;
  }
  return result;
}