Word Counter Class
PHP
Medium
7 views
Problem Description
Given a line, build a WordCounter object and print how many words it has.
Input Format
One line string.
Output Format
One integer.
Official Solution
<?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();
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!