这个问题已经被其他成员询问/回答过,但是我的情况有点不同..如何反转字符串中的单词?
问题:如何反转字符串中的单词?你可以使用strpos(),strlen(),substr()但不是其他非常有用的函数,如explode(),strrev()等。 。
例子:
$字符串= “我是男孩”
答:
“我麻yob”
下面是我的解决方案,我花了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_ws\n";
//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;
}
?>
请求我们为您解答面试问题? :( – 2010-06-04 20:28:25
FWIW,代码对我来说看起来不错 – 2010-06-04 20:30:26
@Ian P:他已经回答了,他问是否有更优雅的方式去做 – webbiedave 2010-06-04 20:33:50