Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

php - How to reverse words in a string?

This question is already asked/answered by other members but my case is a bit different..

Problem: How to reverse words in a string? You can use strpos(), strlen(), substr() but not other very useful functions such as explode(), strrev() etc.

This is basically an interview question so I need to demonstrate ability to manipulate strings.

Example:

$string = "I am a boy"

Answer:

"I ma a yob"

Below is my solution that took me 2 days(sigh) but there gotta be more elegant solution. My code looks very long..

Thanks in advance!

My intention:

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

Code:

<?php

$str = "I am a boy";

echo reverse_word($str) . "
";

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
";

    //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;
}

?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...