开发者

Knowing the length of each sequence in a string

I have a string like this "0011100001100111", and i would like to know the length of each seq开发者_运维问答uence (00, 111, 0000, 11, 00, 111), in the right order.

How can I do that in PHP ?

Thanks to who will help me.


create a loop that loops through the entire string. It would look at each character in the string and compare it to the previous character. If it is the same, then it increases a counter, if it is different, it pushes the counter value onto an array and clears the counter.

Untested code:

function countSequenceLengths($str){
  $counter = 1;
  $lastChar = $str[0];
  $ret = array();
  for($i=1; $i<=strlen($str); $i++){
    if($i<strlen($str) && $str[$i] == $lastChar){
      $counter++;
    }else{
      $ret[] = $counter;
      $counter = 1;
      $lastChar = $str[$i];
    }
  }
  return $ret;
}


You could use a regular expression to do that:

preg_split('/(?<=(.))(?!\\1)/', $str)

Here you’re getting an additional empty string at the end that you just need to remove:

array_slice(preg_split('/(?<=(.))(?!\\1)/', $str), 0, -1)


The code I made, with your help :

$string = "1111100111111001111110011111100111111001111... ...10011111100111111001";

$str = substr($string, 10, 12);

echo "str = '".$str."'&lt;br /&gt;";

$array = array_slice(preg_split('/(?<=(.))(?!\\1)/', $str), 0, -1);

for($i=0; $i&lt;count($array); $i++){

   echo "array[".$i."] = '".$array[$i]."', ";

   echo "array[".$i."] length = '".strlen($array[$i])."'&lt;br /&gt;";

}

returns me the values I needed :

str = '111001111110'

array[0] = '111', array[0] length = '3'

array[1] = '00', array[1] length = '2'

array[2] = '111111', array[2] length = '6'

array[3] = '0', array[3] length = '1'

Thanks a lot !

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜