The content of this article is to introduce the method of converting a string into an integer in PHP (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Problem description
Convert a string to an integer (implement the function of Integer.valueOf(string), but return 0 when the string does not meet the numerical requirements), it is required that a library that cannot use strings to convert integers is required function. If the value is 0 or the string is not a legal value, 0 is returned.
Example 1:
Input: 2147483647
2. Processing positive signs
3. If the string contains non-numeric characters, 0 will be returned directly
4. '0' character The ascii code is 48
4. Traverse the string and start scanning from the 0 position. The current digital character ascii code minus the '0' character ascii code should be the integer at the current position
Algorithm:
StrToInt(str) if empty(str) return 0 symbol=1 if str[0]=='+' symbol=1; str[0]='0' if str[0]=='-' symbol=-1; str[0]='0' res=0 for i=0;i<str.size;i++ if(str[i]<'0' || str[i]>'9') //包含非数字字符的,直接返回0 res=0 break; res=res*10+str[i]-'0' //进位用和ascii相减算出整型数字 res=symbol*res //加上正负号 return res
php implementation (code example):
<?php function StrToInt($str){ if (empty($str)){return 0;} $symbol=1; if ($str{0}=='+'){ $symbol=1; $str{0}='0'; } if ($str[0]=='-'){ $symbol=-1; $str{0}='0'; } $res=0; for ($i=0;$i<strlen($str);$i++){ if($str{$i}<'0' || $str{$i}>'9'){ //包含非数字字符的,直接返回0 $res=0; break; } $res=$res*10+$str{$i}-'0'; //进位用和ascii相减算出整型数字 } $res=$symbol*$res; //加上正负号 return $res; } $s="-123"; $res=StrToInt($s); var_dump($res);
The above is the detailed content of PHP implements a method to convert a string into an integer (code example). For more information, please follow other related articles on the PHP Chinese website!