欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

php字符串反转函数_PHP | 反转给定的字符串而不使用库函数

发布时间:2023/12/1 50 豆豆
生活随笔 收集整理的这篇文章主要介绍了 php字符串反转函数_PHP | 反转给定的字符串而不使用库函数 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

php字符串反转函数

Given a string and we have to reverse it without using a library function.

给定一个字符串,我们必须不使用库函数而将其反转。

Example:

例:

Input: "Hello world!"Output: "!dlrow olleH"Input: "Welcome @ IncludeHelp.Com"Output: "moC.pleHedulcnI @ emocleW"

PHP代码无需使用库函数即可反转字符串 (PHP code to reverse the string without using library function)

<?php //PHP code to reverse the string without //using library function//function definition //it accepts a string and returns the revrse string function reverse_string($text){$rev = ''; //variable to store reverse string$i = 0; //counting length//calculating the length of the string while(isset($text[$i])){$i++;}//accessing the element from the reverse//and, assigning them to the $rev variable for($j = $i - 1; $j >= 0; $j--){$rev .= $text[$j];} //returninig the reversed stringreturn $rev; }//main code i.e. function calling $str = "Hello world!"; $r_str = reverse_string($str); echo "string is: ". $str . "<br/>"; echo "reversed string is: ". $r_str . "<br/>";$str = "Welcome @ IncludeHelp.Com"; $r_str = reverse_string($str); echo "string is: ". $str . "<br/>"; echo "reversed string is: ". $r_str . "<br/>";?>

Output

输出量

string is: Hello world! reversed string is: !dlrow olleH string is: Welcome @ IncludeHelp.Com reversed string is: moC.pleHedulcnI @ emocleW

Explanation:

说明:

Since we can't use the library function, In the function - we run a for loop to reverse the strings by storing the sequence in reverse order in the variable $rev. An additional while loop is set up to check if the variable $text contains a valid string (i.e. to calculate the length). This is an additional safety check to ensure that the program works even if numbers are put into the function.

由于无法使用库函数,因此在函数中,我们运行一个for循环,以相反的顺序将序列存储在变量$ rev中,以反转字符串。 设置了一个附加的while循环,以检查变量$ text是否包含有效的字符串(即,计算长度)。 这是一项附加的安全检查,以确保即使在功能中输入了数字,程序也可以正常运行。

翻译自: https://www.includehelp.com/php/reverse-a-given-string-without-using-the-library-function.aspx

php字符串反转函数

创作挑战赛新人创作奖励来咯,坚持创作打卡瓜分现金大奖

总结

以上是生活随笔为你收集整理的php字符串反转函数_PHP | 反转给定的字符串而不使用库函数的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。