【问题标题】:consecutive occurrence of character连续出现的字符
【发布时间】:2018-09-26 07:33:50
【问题描述】:

字符后跟字符的连续出现次数

例如输入:'zzzyyyyxxxwwvzz'

预期输出:'3z4y3x2w1v2z'

我尝试过的代码

<?php
$str = "zzzyyyyxxxwwvzz";
$strArray = count_chars($str,1);

foreach ($strArray as $key=>$value)
   {
   echo $value.chr($key);
   }
?>

输出为:5z4y3x2w1v

【问题讨论】:

  • 那你累了什么?

标签: php string function character


【解决方案1】:
  • 使用str_split函数,获取数组中给定字符串中的所有字符
  • 现在,使用基本循环和条件,并存储前一个字符,您可以确定是否连续,并据此生成输出字符串。

尝试以下(代码 cmets 中的解释):

$input = 'zzzyyyyxxxwwvzz';

// Split full string into array of single characters
$input_chars = str_split($input);

// initialize some temp variables
$prev_char = '';
$consecutive_count = 0;

$output = '';

// Loop over the characters
foreach ($input_chars as $char) {

    // first time initialize the previous character
    if ( empty($prev_char) ) {
        $prev_char = $char;
        $consecutive_count++;
    } elseif ($prev_char === $char) { // current character matches previous character
        $consecutive_count++;
    } else { // not consecutive character
        // add to output string
        $output .= ($consecutive_count . $prev_char);

        // set current char as new previous_char
        $prev_char = $char;
        $consecutive_count = 1;
    }
}

// handle remaining characters
$output .= ($consecutive_count . $prev_char);
echo $output;

Rextester Demo

【讨论】:

  • 输出是 3z4y3x2w1v 它不包括最后 2 'z'
猜你喜欢
  • 2014-09-29
  • 2015-01-17
  • 1970-01-01
  • 2020-05-06
  • 1970-01-01
  • 1970-01-01
  • 2020-03-05
  • 2020-11-22
  • 2021-01-27
相关资源
最近更新 更多