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

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); //切割字符串,并返回数组
}

你可能感兴趣的:(php)