【问题标题】:Can someone explain to me this 'counting sentences' php code?有人可以向我解释这个“计数句子”的 php 代码吗?
【发布时间】:2018-02-14 17:26:46
【问题描述】:

我的任务是在不使用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

【问题讨论】:

  • 如果这实际上是关于计算句子,那么它就坏了。
  • 它计算的是单词而不是句子,它通过遍历字符串中的每个字符并计算单个空格字符来做到这一点。
  • 嗨哈娜甘尼萨;恐怕你的问题对于这个网站来说太宽泛了。堆栈溢出专为可识别代码问题的精确问答而设计;而您真正要求的是基本编程结构的介绍。这超出了本网站的范围;那里可能有很好的教科书和教程,但恐怕这里不是推荐的地方。

标签: php string count word-count


【解决方案1】:

基本上就是计算一个句子的空格数。

<?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 个单词。

【讨论】:

    【解决方案2】:

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

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

    所以最简单的单词计数算法包括: - $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 个字。

    希望这对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-20
      • 1970-01-01
      • 2022-12-16
      • 2018-03-28
      • 1970-01-01
      • 2011-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多