300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 字符串大写转小写库函数_PHP程序无需使用库函数即可将字符串转换为大写

字符串大写转小写库函数_PHP程序无需使用库函数即可将字符串转换为大写

时间:2022-12-17 09:11:35

相关推荐

字符串大写转小写库函数_PHP程序无需使用库函数即可将字符串转换为大写

字符串大写转小写库函数

Given a string and we have to convert it into uppercase string without using any library function.

给定一个字符串,我们必须在不使用任何库函数的情况下将其转换为大写字符串。

PHP code:

PHP代码:

<?php//function definition//this function accepts a string/text, converts//text to uppercase and return the uppercase converted stringfunction upperCase($str){$chars = str_split($str);$result = '';//loop from 0th character to the last characterfor ($i = 0; $i < count($chars); $i++) {//extracting the character and getting its ASCII value$ch = ord($chars[$i]);//if character is a lowercase alphabet then converting //it into an uppercase alphabetif ($chars[$i] >= 'a' && $chars[$i] <= 'z')$result .= chr($ch - 32);else$result .= $chars[$i];}//finally, returning the stringreturn $result;}//function calling$text = "hello world";echo upperCase($text);echo "<br>";$text = "Hello world!";echo upperCase($text);echo "<br>";$text = "[emailprotected]";echo upperCase($text);echo "<br>";?>

Output

输出量

HELLO WORLDHELLO WORLD![emailprotected]

Code explanation:

代码说明:

We convert the string ($str) into an array of characters ($chars) then calculate their ASCII value using ord() function. Since we know that in ASCII, the Upper Case characters come exactly 32 places before the lower case equivalent, we subtract 32 from the ASCII value and then convert it back to the character using the chr() function. The output is stored in the $result variable.

我们将字符串( $ str )转换为字符数组( $ chars ),然后使用ord()函数计算其ASCII值 。 由于我们知道在ASCII中,大写字符恰好在小写字母之前32位,因此我们从ASCII值减去32,然后使用chr()函数将其转换回字符 。 输出存储在$ result变量中。

This program is a good proof of concept.

该程序是概念的很好证明。

翻译自: /php/convert-string-to-uppercase-without-using-the-library-function.aspx

字符串大写转小写库函数

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。