Word Counter Class

Word Counter Class

Medium PHP PHP OOP Basics 35 views
Explanation Complexity

Problem Statement

Given a line, build a WordCounter object and print how many words it has.

Input Format

One line string.

Output Format

One integer.

Example

I like PHP a lot
5

Constraints

Total chars

Input / Output Format

Input Format
One line string.
Output Format
One integer.
Constraints
Total chars

Examples

Input:
I like PHP a lot
Output:
5

Example Solution (Public)

PHP
<?php
class WordCounter{
  private $text;
  function __construct($t){ $this->text=$t; }
  function count(){
    $t=trim($this->text);
    if($t==='') return 0;
    $tokens=preg_split('/\\s+/', $t);
    return count($tokens);
  }
}
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$wc=new WordCounter($inputText);
echo $wc->count();
?>

Official Solution Code

<?php
class WordCounter{
  private $text;
  function __construct($t){ $this->text=$t; }
  function count(){
    $t=trim($this->text);
    if($t==='') return 0;
    $tokens=preg_split('/\\s+/', $t);
    return count($tokens);
  }
}
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$wc=new WordCounter($inputText);
echo $wc->count();
?>
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.