有人可以向我解释这个'计算句子'的PHP代码吗?

时间:2017-09-06 09:27:17

标签: php string count word-count

我有一项任务是在不使用str_word_count的情况下计算句子,我的大四学生给了我但是我无法理解。有人可以解释一下吗?

我需要了解变量及其工作原理。

<?php

$sentences = "this book are bigger than encyclopedia";

function countSentences($sentences) {
    $y = "";
    $numberOfSentences = 0;
    $index = 0;

    while($sentences != $y) {
        $y .= $sentences[$index];
        if ($sentences[$index] == " ") {
            $numberOfSentences++;
        }
        $index++;
    }
    $numberOfSentences++;
    return $numberOfSentences;
}

echo countSentences($sentences);

?>

输出

  

6

2 个答案:

答案 0 :(得分:0)

基本上,它只是计算一个句子中的空格数。

<?php

  $sentences = "this book are bigger than encyclopedia";

  function countSentences($sentences) {
    $y = ""; // Temporary variable used to reach all chars in $sentences during the loop
    $numberOfSentences = 0; // Counter of words
    $index = 0; // Array index used for $sentences

    // Reach all chars from $sentences (char by char)
    while($sentences != $y) {
      $y .= $sentences[$index]; // Adding the current char in $y

      // If current char is a space, we increase the counter of word
      if ($sentences[$index] == " "){
        $numberOfSentences++;
      }

      $index++; // Increment the index used with $sentences in order to reach the next char in the next loop round
    }

    $numberOfSentences++; // Additional incrementation to count the last word
    return $numberOfSentences;
  }

  echo countSentences($sentences);

?>

请注意,此函数在多种情况下会产生错误的结果,例如,如果您有两个空格,则此函数将计算2个单词而不是一个。

答案 1 :(得分:0)

这是非常微不足道的事情,我会说。 任务是计算句子中的单词。句子是一个字母(一系列字符),是字母或空格(空格,换行等)......

现在,这句话的一句话是什么?它是一组独特的字母,“不接触”其他字母组;意思是单词(字母组)用空格分隔(假设只是一个普通的空格)

因此,计算单词的最简单算法包括: - $ words_count_variable = 0 - 逐个浏览所有角色 - 每次找到空格时,就意味着在此之前刚刚结束的新单词,你必须增加$ words_count_variable - 最后,你会发现字符串的结尾,这意味着在此之前刚刚结束的一个单词,所以你最后一次增加你的$ words_count_variable

取“这是一句话”。

We set $words_count_variable = 0;

Your while cycle will analyze:
"t"
"h"
"i"
"s"
" " -> blank space: a word just ended -> $words_count_variable++ (becomes 1)
"i"
"s"
" " -> blank space: a word just ended -> $words_count_variable++ (becomes 2)
"a"
" " -> blank space: a word just ended -> $words_count_variable++ (becomes 3)
"s"
"e"
"n"
...
"n"
"c"
"e"
-> end reached: a word just ended -> $words_count_variable++ (becomes 4)

所以,4。 计算4个字。

希望这有用。