Three reverse sorting methods except strrev () are interpreted. The PHP function strrev () test code is as follows: header (Content-type: texthtml; charsetutf-8); $ strimplode (, range (9,0 )); prin we are using
For the reverse sorting of strings, the test code of the PHP function strrev () is as follows:
- Header ('content-type: text/html; charset = utf-8 ');
- $ Str = implode ('', range (9, 0 ));
- Print '<p>Before reversed:'. $ Str.' </p> ';
- Print '<p> <strong> After reversed: </strong>'. strrev ($ str). '</p> ';
- /*
- The output is as follows:
- Beforereversed: 9876543210
- After reversed: 0123456789
- */
How can I implement strrev () without the built-in PHP function? Three methods (bipartite, cyclic, and recursive) were tested, but no performance tests were conducted.
1. binary classification
- /**
- * The binary method is used to sort strings in reverse order.
- * @ Param string $ str Source string
- * @ Return string returns the reverse string.
- */
- Function reverse ($ str = ''){
- $ Len = strlen ($ str); // you cannot use count or sizeof.
- $ Mid = floor ($ len/2 );
- For ($ I = 0; $ I <$ mid; $ I ++ ){
- $ Temp = $ str [$ I];
- $ Str [$ I] = $ str [$ len-$ i-1];
- $ Str [$ len-$ i-1] = $ temp;
- }
- Return $ str;
- }
2. circulation method
- /**
- * Cyclically arrange strings in reverse order (efficiency is lower than that of the binary method)
- * @ Param string $ str Source string
- * @ Return string returns the reverse string.
- */
- Function reverse ($ str = ''){
- $ Result = '';
- For ($ I = 1; $ I <= strlen ($ str); $ I ++ ){
- $ Result. = substr ($ str,-$ I, 1 );
- }
- Return $ result;
- }
3. recursion
- /**
- * Recursively arrange strings in reverse order (low efficiency)
- * @ Param string $ str Source string
- * @ Return string returns the reverse string.
- */
- Function reverse ($ str = ''){
- Static $ result = '';
- /* Use stacks to understand recursive calls */
- If (strlen ($ str)> 0 ){
- Reverse (substr ($ str, 1 ));
- $ Result. = substr ($ str, 0, 1); // The sentence must be placed after the previous statement.
- }
- Return $ result;
- }
The above is the specific usage of the PHP function strrev () and the implementation of the other three methods in reverse order.
The PHP function strrev () has the following test code: header ('content-type: text/html; charset = utf-8 '); $ str = implode ('', range (9, 0); prin...