检查单词是否由连续字母组成


Check words if they are composed of Consecutive Alphabetic Characters

我接受一个句子作为输入,如下所示:

abcd 01234 87 01235

接下来,我必须检查每个单词,看看它的字符在字母表中是否连续。输出如下:

abcd 01234

嗯,01235包含连续的字符,但整个单词也包含非连续的字符(35),所以它不会打印在屏幕上。

到目前为止,我写的是:

function string_to_ascii($string)
{
    $ascii = NULL;
    for ($i = 0; $i < strlen($string); $i++)
    {
        $ascii[] =  ord($string[$i]);
    }
    return($ascii);
}

$input = "abcd 01234 87 01235";
//first, we split the sentence into separate words
$input = explode(" ",$input);
foreach($input as $original_word)
{
    //we need it clear
    unset($current_word);
    //convert current word into array of ascii chars
    $ascii_array = string_to_ascii($original_word);
    //needed for counting how many chars are already processed
    $i = 0;
    //we also need to count the total number chars in array
    $ascii_count = count($ascii_array);
     //here we go, checking each character from array
     foreach ($ascii_array as $char)
     {
        //if IT'S THE LAST WORD'S CHAR
        if($i+1 == $ascii_count)
        {
            //IF THE WORD HAS JUST 1 char, output it
            if($ascii_count == 1)
            {
                $current_word  .= chr($char);
            }
            //IF THE WORDS HAS MORE THAN 1 CHAR
            else
            {
                //IF PREVIOUS CHAR CODE IS (CURRENT_CHAR-1)  (CONSECUTIVE, OUTPUT IT)
                if(($char - 1) == $ascii_array[($i-1)])
                {
                    $current_word .=chr($char);
                }
            }
        }
        //IF WE AREN'T YET AT THE ENDING
        else
        {
            //IF NEXT CHAR CODE IS (CURRENT_CHAR+1) (CONSECUTIVE, OUTPUT IT)
            if(($char + 1) == ($ascii_array[($i+1)]))
            {
                $current_word .=chr($char);
            }
        }
        $i++;
     }
    //FINALLY, WE CHECK IF THE TOTAL NUMBER OF CONSECUTIVE CHARS is the same as THE NUMBER OF CHARS
    if(strlen($current_word) == strlen($original_word))
    {
        $output[] = $current_word;
    }
}
//FORMAT IT BACK AS SENTENCE
print(implode(' ',$output));

但也许还有另一种方法可以做到这一点,更简单?

抱歉拼写错误

这很有效。。。

$str = 'abcd 01234 87 01235';
$words = explode(' ', $str);
foreach($words as $key => $word) {
    if ($word != implode(range($word[0], chr(ord($word[0]) + strlen($word) - 1)))) {
       unset($words[$key]);
    }
}
echo implode(' ', $words);

CodePad。

基本上,它获取每个单词的第一个字符,并创建字符范围,如果单词由连续字符组成,则字符范围将为值。

然后进行简单的字符串比较。

要获得更高性能的版本。。。

$str = 'abcd 01234 87 01235';
$words = explode(' ', $str);
foreach($words as $key => $word) {
    foreach(str_split($word) as $index => $char) {
      $thisOrd = ord($char); 
      if ($index > 0 AND $thisOrd !== $lastOrd + 1) {
         unset($words[$key]);
         break;
      }
      $lastOrd = $thisOrd;
    }
}
echo implode(' ', $words);

CodePad。

这两个例子都依赖于字符的序数对于连续字符是连续的。ASCII就是这种情况,但我不确定其他字符。