其他成员已经提出/回答了这个问题,但我的情况有点不同......
问题:如何反转字符串中的单词?你可以使用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_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;
}
?>
答案 0 :(得分:17)
$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
答案 1 :(得分:2)
糟糕!误读了这个问题。在这里(注意,这将分割在所有非字母边界上,而不仅仅是空格。如果你想要一个字符不被拆分,只需将它添加到$wordChars
):
function revWords($string) {
//We need to find word boundries
$wordChars = 'abcdefghijklmnopqrstuvwxyz';
$buffer = '';
$return = '';
$len = strlen($string);
$i = 0;
while ($i < $len) {
$chr = $string[$i];
if (($chr & 0xC0) == 0xC0) {
//UTF8 Characer!
if (($chr & 0xF0) == 0xF0) {
//4 Byte Sequence
$chr .= substr($string, $i + 1, 3);
$i += 3;
} elseif (($chr & 0xE0) == 0xE0) {
//3 Byte Sequence
$chr .= substr($string, $i + 1, 2);
$i += 2;
} else {
//2 Byte Sequence
$i++;
$chr .= $string[$i];
}
}
if (stripos($wordChars, $chr) !== false) {
$buffer = $chr . $buffer;
} else {
$return .= $buffer . $chr;
$buffer = '';
}
$i++;
}
return $return . $buffer;
}
编辑:现在它只是一个函数,并以反向表示法存储缓冲区。
Edit2:现在处理UTF8字符(只需在$wordChars
字符串中添加“字”字符)...
答案 2 :(得分:1)
我认为最简单的方法是使用explode()和使用array_reverse()函数将字符串插入数组中。当然你必须输出数组。有关array_reverse()的更多详细信息,请参阅http://php.net/manual/en/function.array-reverse.php
答案 3 :(得分:0)
如果PHP使用连接语法,它可以以更优雅的方式完成:)
{
"" "" 3 roll
{
dup " " ==
{ . . "" }
{ swp . }
ifelse }
foreach .
} "reverse" function
"I am a boy" reverse echo // Prints "I ma a yob"
答案 4 :(得分:0)
$str = "Hello how are you";
$teststr = explode(" ",$str);
for($i=count($teststr)-1;$i>=0;$i--){
echo $teststr[$i]." ";
}
Output : you are how hello
答案 5 :(得分:0)
<?php
// Reversed string and Number
// For Example :
$str = "hello world. This is john duvey";
$number = 123456789;
$newStr = strrev($str);
$newBum = strrev($number);
echo $newStr;
echo "<br />";
echo $newBum;
OUTPUT :
first : yevud nhoj si sihT .dlrow olleh
second: 987654321
答案 6 :(得分:0)
我的答案是计算字符串长度,将字母拆分成一个数组,然后向后循环。这也是检查单词是否为回文的好方法。这只能用于常规字符串和数字。
preg_split也可以更改为explode()。
/**
* Code snippet to reverse a string (LM)
*/
$words = array('one', 'only', 'apple', 'jobs');
foreach ($words as $d) {
$strlen = strlen($d);
$splits = preg_split('//', $d, -1, PREG_SPLIT_NO_EMPTY);
for ($i = $strlen; $i >= 0; $i=$i-1) {
@$reverse .= $splits[$i];
}
echo "Regular: {$d}".PHP_EOL;
echo "Reverse: {$reverse}".PHP_EOL;
echo "-----".PHP_EOL;
unset($reverse);
}
答案 7 :(得分:0)
不使用任何功能。
$string = 'I am a boy';
$newString = '';
$temp = '';
$i = 0;
while(@$string[$i] != '')
{
if($string[$i] == ' ') {
$newString .= $temp . ' ';
$temp = '';
}
else {
$temp = $string[$i] . $temp;
}
$i++;
}
$newString .= $temp . ' ';
echo $newString;
输出:我是个傻子
答案 8 :(得分:-1)
编辑:您要求翻转每个单词,但仍按“单词”顺序排列。这样的事情可能会更好:
$string = "I am a boy!";
$array = explode(" ", $string);
foreach ($array as &$word) {
$word = strrev($word);
}
$rev_string = implode(" ", $array);
答案 9 :(得分:-1)
Settings > Startup > Environment