编程挑战:在不使用循环或本机反转函数的情况下反转字符串

发布于 2024-10-16 02:12:28 字数 230 浏览 3 评论 0原文

如何编写一个简短的 PHP 函数来反转字符串?

该函数必须:

  • 只有一个参数,
  • 不使用内置函数 strrev()array_reverse(),并且
  • 不使用 for( 等循环结构)foreach()while()

How would you write a short PHP function to reverse a string?

The function must:

  • have only one argument,
  • not use the built-in function strrev() or array_reverse(), and
  • not use a looping construct like for(), foreach() or while().

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

南城旧梦 2024-10-23 02:12:28

赶紧往下扫,这些看起来好长啊!

function rev($str) {
    return $str?rev(substr($str,1)).$str[0]:'';
}

递归显然不适用于长度超过 100 个字符的字符串。

Quickly scanning down, these all look so long!

function rev($str) {
    return $str?rev(substr($str,1)).$str[0]:'';
}

Recursive so obviously doesn't work on strings longer than 100 chars.

神仙妹妹 2024-10-23 02:12:28

因为这听起来像是家庭作业问题,我会告诉你如何做,但你自己编码。
通过强制转换将字符串转换为数组。然后使用采用用户定义的排序函数的数组排序函数之一。

Since this sounds like homework question I'll tell you how but you code it yourself.
Turn the string into an array with a cast. Then use one of the array sorting functions that takes a user defined sorting function.

日裸衫吸 2024-10-23 02:12:28
function reverseString($string) {
  return shell_exec(sprintf('ruby -e \'puts "%s".reverse\'', preg_replace("/\"/", "\\\"", $string)));
}
function reverseString($string) {
  return shell_exec(sprintf('ruby -e \'puts "%s".reverse\'', preg_replace("/\"/", "\\\"", $string)));
}
幸福丶如此 2024-10-23 02:12:28

递归解决方案:

function sr( $txt ){
    return $txt[ strlen( $txt ) - 1 ] . ( ( strlen( $txt ) > 1 )?sr( substr( $txt, 0, strlen($txt)-1 ) ):null) ;
}

echo sr( "abc def ghi jklm" );

说明:

return $txt[ strlen( $txt ) - 1 ] // return last byte of string
.                                 // concatenate it with:
(( strlen( $txt ) > 1 ) ?         // if there are more bytes in string
 sr( substr( $txt, 0, strlen( $txt ) - 1 ) // then with reversed string without last letter
 : null );                        // otherwise with null

为了使其适用于零长度字符串,添加了另一个条件表达式:

return (strlen($txt))? ($txt[ strlen( $txt ) - 1 ] . ( ( strlen( $txt ) > 1 )?sr( substr( $txt, 0, strlen($txt)-1 ) ):null)):"" ;

Recursive solution:

function sr( $txt ){
    return $txt[ strlen( $txt ) - 1 ] . ( ( strlen( $txt ) > 1 )?sr( substr( $txt, 0, strlen($txt)-1 ) ):null) ;
}

echo sr( "abc def ghi jklm" );

Explanation:

return $txt[ strlen( $txt ) - 1 ] // return last byte of string
.                                 // concatenate it with:
(( strlen( $txt ) > 1 ) ?         // if there are more bytes in string
 sr( substr( $txt, 0, strlen( $txt ) - 1 ) // then with reversed string without last letter
 : null );                        // otherwise with null

To make it work with zero-length string, another conditional expression was added:

return (strlen($txt))? ($txt[ strlen( $txt ) - 1 ] . ( ( strlen( $txt ) > 1 )?sr( substr( $txt, 0, strlen($txt)-1 ) ):null)):"" ;
晨光如昨 2024-10-23 02:12:28
    <?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`enter code here`
    <?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`enter code here`
糖果控 2024-10-23 02:12:28

满足您的所有要求,但仅适用于 PHP 5.3 或更高版本。让它对其他人起作用是家庭作业。

function reverse($str) {
        $i=0;
        $j=strlen($str)-1;
start:
        if($i>=$j) {
                goto done;
        }
        $tmp = $str[$j];
        $str[$j--] = $str[$i];
        $str[$i++] = $tmp;
        goto start;
done:
        return $str;
}   

Meets all your requirements but works only in PHP 5.3 or higher. Making it work on others is left as homework.

function reverse($str) {
        $i=0;
        $j=strlen($str)-1;
start:
        if($i>=$j) {
                goto done;
        }
        $tmp = $str[$j];
        $str[$j--] = $str[$i];
        $str[$i++] = $tmp;
        goto start;
done:
        return $str;
}   
半透明的墙 2024-10-23 02:12:28
function reverse_string($string) {
    if($string !== '')
        return substr($string, -1).reverse_string(substr($string, 0, strlen($string)-2));     
}
function reverse_string($string) {
    if($string !== '')
        return substr($string, -1).reverse_string(substr($string, 0, strlen($string)-2));     
}
心房敞 2024-10-23 02:12:28

递归解决方案。感觉就像你的老师正在寻找的东西一样。

function my_strrev ($str) {
  $length = strlen($str);
  switch ($length) {
      case 0: return '';
      case 1: return $str; break;
      case 2: return $str[1] . $str[0];
      default :
          return $str[$length-1] .  my_strrev(substr($str,1,-1)) . $str[0];
          break;
  }
}

它交换第一个和最后一个字母,然后与字符串的其余部分相同。

更新:
受 mateusza 的启发,我创建了另一个解决方案(很有趣;))

function my_strrev2 ($str) {
  return $str
    ? my_strrev2(substr($str, 1)) . $str[0]
    : '';
}

它的工作原理与 mateuszas 类似,但这个解决方案附加第一个字符,而不是在最后一个字符前面。

A recursive solution. Feels like something like that is what your teacher is looking for.

function my_strrev ($str) {
  $length = strlen($str);
  switch ($length) {
      case 0: return '';
      case 1: return $str; break;
      case 2: return $str[1] . $str[0];
      default :
          return $str[$length-1] .  my_strrev(substr($str,1,-1)) . $str[0];
          break;
  }
}

It swaps the first and the last letter and than makes the same with the rest of the string.

Update:
Inspired by mateusza I created another solution (its fun ;))

function my_strrev2 ($str) {
  return $str
    ? my_strrev2(substr($str, 1)) . $str[0]
    : '';
}

It works similar to mateuszas, but this one appends the first character, instead of prepend the last one.

忘羡 2024-10-23 02:12:28

在 PHP 中不使用任何函数:

$String = "Hello World";

$i = 0;

// Find the end of the string
while (isset($String[$i])) {
    $i++;
}

// Decrement $i to point to the last character
$i--;


// Build the reversed string
while ($i >= 0) {
    $reversed .= $String[$i];
    $i--;
}

echo "Reversed :- $reversed"  ;

In PHP without using any function:

$String = "Hello World";

$i = 0;

// Find the end of the string
while (isset($String[$i])) {
    $i++;
}

// Decrement $i to point to the last character
$i--;


// Build the reversed string
while ($i >= 0) {
    $reversed .= $String[$i];
    $i--;
}

echo "Reversed :- $reversed"  ;
一身骄傲 2024-10-23 02:12:28

为了避免递归的字符串长度限制,您可以对非黑名单函数使用三个步骤。

  1. 分割成一个数组。
  2. 按键降序排序。
  3. 爆破阵列。

代码:(演示

function revStr(string $str): string
{
    $str = str_split($str);
    krsort($str);
    return implode($str);
}

echo revStr('SnackOverflow');  // wolfrevOkcanS

作为 IIFE:

echo (
      function($str) {
          $str = str_split($str);
          krsort($str);
          return implode($str);
      }
     )('SnackOverflow');

To avoid the string length limitations of recursion, you can use three steps with non-blacklisted functions.

  1. Split into an array.
  2. Sort by keys descending.
  3. Implode the array.

Code: (Demo)

function revStr(string $str): string
{
    $str = str_split($str);
    krsort($str);
    return implode($str);
}

echo revStr('SnackOverflow');  // wolfrevOkcanS

As an IIFE:

echo (
      function($str) {
          $str = str_split($str);
          krsort($str);
          return implode($str);
      }
     )('SnackOverflow');
七颜 2024-10-23 02:12:28

我的答案是OOP并使用递归。自行处理递归限制。

class StringReverser
{
    public $reversed_string;
    public function __construct ($string) {
        $original_recursion_limit = ini_get('pcre.recursion_limit');
        $array = str_split($string);
        krsort($array);
        $i = strlen($string);
        ini_set('pcre.recursion_limit', $i+1);
        $this->add2string($string, $i, $array);
        ini_set('pcre.recursion_limit', $original_recursion_limit);
    }

    public function reverse() {
        return $this->reversed_string;
    }

    private function add2string ($s, $i,  $a) {
        if($i) {
            $i--;
            $this->reversed_string .= $a[$i];
            $this->add2string($s, $i,$a, $this->reversed_string);
        }
    }
}


$string =  "Elzo Valugi";
echo $string ."<br>";
$reverser = new StringReverser($string);
echo $reverser->reverse();

My answer is OOP and uses recursion. Takes care by itself of the recursion limit.

class StringReverser
{
    public $reversed_string;
    public function __construct ($string) {
        $original_recursion_limit = ini_get('pcre.recursion_limit');
        $array = str_split($string);
        krsort($array);
        $i = strlen($string);
        ini_set('pcre.recursion_limit', $i+1);
        $this->add2string($string, $i, $array);
        ini_set('pcre.recursion_limit', $original_recursion_limit);
    }

    public function reverse() {
        return $this->reversed_string;
    }

    private function add2string ($s, $i,  $a) {
        if($i) {
            $i--;
            $this->reversed_string .= $a[$i];
            $this->add2string($s, $i,$a, $this->reversed_string);
        }
    }
}


$string =  "Elzo Valugi";
echo $string ."<br>";
$reverser = new StringReverser($string);
echo $reverser->reverse();
白云悠悠 2024-10-23 02:12:28
<?php
 $string="jomon is name my";
 for($i=strlen($string);$i>=0;$i--)
 {
     $char.=$string{$i};    
 }
 echo $char."<br/>";

 for($i=0; $i<strlen($char);$i++)
 {
     if($char[$i+1]==" " || $char[$i+1]=="")
     {
         for($temp=$i; $temp>=0 && $char[$temp]!=' '; $temp--)
             echo $char[$temp];
     }
     echo " ";
 }    
 ?>
<?php
 $string="jomon is name my";
 for($i=strlen($string);$i>=0;$i--)
 {
     $char.=$string{$i};    
 }
 echo $char."<br/>";

 for($i=0; $i<strlen($char);$i++)
 {
     if($char[$i+1]==" " || $char[$i+1]=="")
     {
         for($temp=$i; $temp>=0 && $char[$temp]!=' '; $temp--)
             echo $char[$temp];
     }
     echo " ";
 }    
 ?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文