好玩的线上检测代码工具-codewars(3)

来源:互联网 发布:手机知乎如何关注话题 编辑:程序博客网 时间:2024/05/01 11:54

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

Examples:

solution(‘abc’) // should return [‘ab’, ‘c_’]
solution(‘abcdef’) // should return [‘ab’, ‘cd’, ‘ef’];

function solution($str) {  //每两个字符为一个单位,重新放到新的数组中  if(strlen($str) == 0)  {    return [];  }  $new_str = '';  if(strlen($str) % 2 == 0)  {    $new_str = $str;  }  else{     $new_str = $str . '_';  }  return str_split($new_str, 2); //切割字符串,并返回数组}