私はPHP開発の初心者であり、ついには特定の文字数が最大の文章で単語を見つけるプログラムを書くことができました。以下は最大の特定の文字数を持つ文章内の単語を見つける
は、私が試したものです:
<?php
// Program to find the word in a sentence with maximum specific character count
// Example: "O Romeo, Romeo, wherefore art thou Romeo?”
// Solution: wherefore
// Explanation: Because "e" came three times
$content = file_get_contents($argv[1]); // Reading content of file
$max = 0;
$arr = explode(" ", $content); // entire array of strings with file contents
for($x =0; $x<count($arr); $x++) // looping through entire array
{
$array[$x] = str_split($arr[$x]); // converting each of the string into array
}
for($x = 0; $x < count($arr); $x++)
{
$count = array_count_values($array[$x]);
$curr_max = max($count);
if($curr_max > $max)
{
$max = $curr_max;
$word = $arr[$x];
}
}
echo $word;
?>
質問:私はPHPの開発に新しいですので、私は最適化手法を知りません。とにかく私はこのコードを最適化できますか?また、regexを使ってこのコードをさらに最適化することはできますか?親切にガイドします。
「特定の文字数」とは、具体的にはどういう意味ですか? –
混乱して申し訳ありません。別の例: "abc abbc eeea"。 eが3回来ると答えは "eeea"になります。 – Unbreakable
は、 'for'ループの代わりに' foreach'を使ってどうやって言い換えることができますか分かりません。 'preg_split'を使用して文字列を文字以外の文字に分割します。最後に 'count_chars'を' strtolower'と使用してください –