不使用本机拆分或反转函数来反转字符串中每个单词中的字母 [英] Reverse letters in each word of a string without using native splitting or reversing functions

查看:139
本文介绍了不使用本机拆分或反转函数来反转字符串中每个单词中的字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这项任务已经有人问过/回答了,但我最近参加了一次工作面试,提出了一些额外的挑战,以展示我操纵字符串的能力。

问题:如何颠倒字符串中的单词?您可以使用strpos()strlen()substr(),但不能使用其他非常有用的函数,如explode()strrev()等。

示例:

$string = "I am a boy"

答案:

I ma a yob

下面是我花了两天时间进行的编码尝试[叹息],但肯定有更优雅、更简洁的解决方案。

意图:

1. get number of words
2. based on word count, grab each word and store into array
3. loop through array and output each word in reverse order

编码:

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

推荐答案

$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

这篇关于不使用本机拆分或反转函数来反转字符串中每个单词中的字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆