Reverse string without strrev

前端 未结 23 985
忘了有多久
忘了有多久 2020-12-13 13:19

Some time ago during a job interview I got the task to reverse a string in PHP without using strrev.

My first solution was something like this:

23条回答
  •  温柔的废话
    2020-12-13 14:18

    public function checkString($str){
        if(!empty($str)){ 
            $i = 0;
            $str_reverse = '';
    
            while(isset($str[$i])){ 
                $strArr[] = $str[$i];
                $i++;
            }
            for($j = count($strArr); $j>= 0; $j--){ 
                if(isset($strArr[$j])){
                    $str_reverse .= $strArr[$j];
                }
            }
            if($str == $str_reverse){ 
                echo 'It is a correct string';
            }else{
                echo 'Invalid string';
            }
        }
        else{
            echo 'string not found.';
        }
    }
    

提交回复
热议问题