以前に作成した SimpleNotepad
クラスを修正します。
get_word_count
メソッドを追加する
SimpleNotepad
クラスの仕様は以下のとおりです。
プロパティ | 意味 |
---|---|
$input_string |
入力された文字列 |
メソッド | 処理内容 |
---|---|
type |
$string 引数で受け取った文字列データを $input_string プロパティに追加するただし $input_string プロパティに文字列データが存在する場合は " " 半角スペースを付けてから追加する |
show |
$input_string プロパティの内容を出力する |
get_input_string_length |
$input_string プロパティの文字列の長さを取得する |
get_word_count |
$input_string プロパティに含まれる単語の数を取得する |
コンストラクタ | 処理内容 |
---|---|
__construct |
$input_string プロパティを "" 空文字で初期化する |
問題 4
次のプログラム( notepad_runner4.php
)があります。
notepad_runner4.php
<?php
require_once("SimpleNotepad.php");
$notepad = new SimpleNotepad();
$notepad->type("one");
$notepad->type("two");
$notepad->type("three");
$notepad->show(); # => "one two three"
$length = $notepad->get_input_string_length();
echo $length . PHP_EOL; # => 13
$word_count = $notepad->get_word_count();
echo $word_count . PHP_EOL; # => 3
次の実行結果のとおり動作するプログラム( SimpleNotepad.php
)を作成してください。
実行結果
$ php notepad_runner4.php
one two three
13
3
SimpleNotepad.php
<?php
class SimpleNotepad
{
protected $input_string;
public function __construct()
{
$this->input_string = "";
}
public function type($string)
{
if ($this->input_string) {
$this->input_string .= " ";
}
$this->input_string .= $string;
}
public function show()
{
echo $this->input_string . PHP_EOL;
}
public function get_input_string_length()
{
return mb_strlen($this->input_string);
}
# TODO define get_word_count method.
}
get_word_count
メソッドを定義してください。
ヒント
$input_string
プロパティには " "
で区切られて単語が格納されています。 explode
関数を使えば " "
で区切って文字列を配列に変換できます。その配列の要素数は単語の数に等しくなります。