簡體   English   中英

有人可以向我解釋這個“計數句子”的 php 代碼嗎?

[英]Can someone explain to me this 'counting sentences' php code?

我有一項不使用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

  $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 個。

我會說,這是一件非常微不足道的事情。 任務是計算句子中的單詞 句子是由字母或空格(空格、換行等)組成的字符串(字符序列)...

現在,這句話的一個詞是什么? 它是一組獨特的字母,“不接觸”其他字母組; 意思是單詞(字母組)用空格彼此分開(假設只是一個普通的空格)

所以最簡單的單詞計數算法包括: - $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 個字算了。

希望這是有幫助的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM