字符串大写转小写库函数
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 string
function upperCase($str)
{
$chars = str_split($str);
$result = '';
//loop from 0th character to the last character
for ($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 alphabet
if ($chars[$i] >= 'a' && $chars[$i] <= 'z')
$result .= chr($ch - 32);
else
$result .= $chars[$i];
}
//finally, returning the string
return $result;
}
//function calling
$text = "hello world";
echo upperCase($text);
echo "<br>";
$text = "Hello world!";
echo upperCase($text);
echo "<br>";
$text = "[email protected]";
echo upperCase($text);
echo "<br>";
?>
Output
输出量
HELLO WORLD
HELLO WORLD!
[email protected]
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.
该程序是概念的很好证明。
翻译自: https://www.includehelp.com/php/convert-string-to-uppercase-without-using-the-library-function.aspx
字符串大写转小写库函数