Michel L'HUILLIER
Michel L'HUILLIER

Reputation: 11

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 sequence (00, 111, 0000, 11, 00, 111), in the right order.

How can I do that in PHP ?

Thanks to who will help me.

Upvotes: 0

Views: 94

Answers (3)

Michel L'HUILLIER
Michel L'HUILLIER

Reputation: 11

The code I made, with your help :

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

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

echo "str = '".$str."'<br />";

$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 !

Upvotes: 1

Marius
Marius

Reputation: 58911

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;
}

Upvotes: 5

Gumbo
Gumbo

Reputation: 655169

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)

Upvotes: 2

Related Questions