利用递归反转字符串(从左到右)

1.C(PHP底层实现)

/* {{{ proto string strrev(string str)
   Reverse a string */
PHP_FUNCTION(strrev)
{
    zend_string *str;
    char *e, *p;
    zend_string *n;

    if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &str) == FAILURE) {
        return;
    }

    n = zend_string_alloc(ZSTR_LEN(str), 0);
    p = ZSTR_VAL(n);

    e = ZSTR_VAL(str) + ZSTR_LEN(str); //e是字符串str的最末尾字符的地址

    while (--e >= ZSTR_VAL(str)) {
        *p++ = *e;
    }

    *p = '\0';

    RETVAL_NEW_STR(n);
}
/* }}} */

2.C

void revString2(char *str,char *target){
   int len = sizeof(char)*strlen(str);
   char *e;
   e = str+len;
   while(e-- >= str ){
       *target++ = *e;
   }
}

 

2.PHP

//反转一个字符串
function reverseString($string,$len=0,&$target=''){
    $num = strlen($string);
    if($num==0)
        return;
    if($num==$len){
        //$target=$arr[$len-1];
        return 0;
    }
    $len++;
    reverseString($string,$len,$target);
    $target.=substr($string,$len-1,1);
}

//$arr = ['h','e','l','l','o','w','o','r','l','d'];
$string = 'helloworld';
$target = '';
reverseString($string,0,$target);

print_r($target);

 

posted @ 2021-02-05 00:16  不知起什么名字  阅读(197)  评论(0编辑  收藏  举报