2017-09-06 49 views
0

我有一个任务来计算句子而不使用str_word_count,我的前辈给了我但我无法理解。有人可以解释吗?有人可以向我解释这个'计算句子'的PHP代码?

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

<?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); 

?> 

输出是

+4

如果这实际上是关于计算句子,那么它就被打破了。 –

+0

它计算单词而不是句子,它通过逐行扫描字符串中的每个字符并计算单个空格字符来完成此操作。 –

+0

嗨Hana Ganesa;恐怕你的问题对于这个网站来说太广泛了。堆栈溢出专为精确的问题和对可识别代码问题的回答而设计;而你真正要求作为基本编程结构的介绍。这超出了本网站的范围;那里可能有很好的教科书和教程,但这里并不是我担心的地方。 –

回答

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个字数。

希望这有帮助。

0

Basicaly,它只是计数在一个句子的空间的数量。

<?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个单词而不是一个单词。

相关问题