php – 如何反转字符串中的单词?
发布时间:2020-12-13 13:38:39 所属栏目:PHP教程 来源:网络整理
导读:其他成员已经提出/回答了这个问题,但我的情况有点不同…… 问题:如何反转字符串中的单词?你可以使用strpos(),strlen(),substr()但不能使用其他非常有用的函数,比如explode(),strrev()等. 这基本上是一个面试问题所以我需要展示操纵字符串的能力. 例: $str
其他成员已经提出/回答了这个问题,但我的情况有点不同……
问题:如何反转字符串中的单词?你可以使用strpos(),strlen(),substr()但不能使用其他非常有用的函数,比如explode(),strrev()等. 这基本上是一个面试问题所以我需要展示操纵字符串的能力. 例: $string =“我是个男孩” 回答: “我是一个人” 以下是我的解决方案,花了我2??天(叹气),但必须有更优雅的解决方案.我的代码看起来很长.. 提前致谢! 我的本意: 1. get number of word 2. based on number of word count,grab each word and store into array 3. loop through array and output each word in reverse order 码: <?php $str = "I am a boy"; echo reverse_word($str) . "n"; function reverse_word($input) { //first find how many words in the string based on whitespace $num_ws = 0; $p = 0; while(strpos($input," ",$p) !== false) { $num_ws ++; $p = strpos($input,' ',$p) + 1; } echo "num ws is $num_wsn"; //now start grabbing word and store into array $p = 0; for($i=0; $i<$num_ws + 1; $i++) { $ws_index = strpos($input,$p); //if no more ws,grab the rest if($ws_index === false) { $word = substr($input,$p); } else { $length = $ws_index - $p; $word = substr($input,$p,$length); } $result[] = $word; $p = $ws_index + 1; //move onto first char of next word } print_r($result); //append reversed words $str = ''; for($i=0; $i<count($result); $i++) { $str .= reverse($result[$i]) . " "; } return $str; } function reverse($str) { $a = 0; $b = strlen($str)-1; while($a < $b) { swap($str,$a,$b); $a ++; $b --; } return $str; } function swap(&$str,$i1,$i2) { $tmp = $str[$i1]; $str[$i1] = $str[$i2]; $str[$i2] = $tmp; } ?> $string = "I am a boy"; $reversed = ""; $tmp = ""; for($i = 0; $i < strlen($string); $i++) { if($string[$i] == " ") { $reversed .= $tmp . " "; $tmp = ""; continue; } $tmp = $string[$i] . $tmp; } $reversed .= $tmp; print $reversed . PHP_EOL; >> I ma a yob (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |