不使用内置PHP函数的简单算法?

时间:2016-07-14 22:29:09

标签: php algorithm

我打算生成一个简单的算法,但我被要求不使用内置的PHP函数。请帮帮忙?

主文件看起来像这样(main.php):

<?php
    $myfile = "in.txt";
    $lines = file($myfile);
    $line1 = $lines[0];
    $line2 = $lines[1];
    $newtext = wordwrap($line2, $line1, "\n", false);
    $fh = fopen('out.txt', 'w');
    fwrite($fh, $newtext);
?>

它应该采用一个看起来像这样的文件(in.txt):

15 
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi semper, est non gravida venenatis, est neque fringilla quam, hendrerit ultrices justo turpis nec augue.

并添加换行符,每行包含X个字符(本例中为15)

最终产品看起来像这样(out.txt):

Lorem ipsum
dolor sit amet,
consectetur
adipiscing
elit. Morbi
semper, est non
gravida
venetatis, est
negue fringilla
quam, hendrerit
ultrices justo
turpis nec
augue.

如何在不使用这些预制PHP函数的情况下创建此算法?

2 个答案:

答案 0 :(得分:0)

在此代码中,我尝试不使用strlen()substr()(甚至str_split() / array_splice())等功能。结果是这样的:

$qt = 15; // with how many chars to break the string
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi semper, est non gravida venenatis, est neque fringilla quam, hendrerit ultrices justo turpis nec augue.';

$result = '';
$c = 0;
$nl = '<br>'; // the break (could be /n, PHP_EOL, etc)

while(isset($text[$c])){ // avoid using built-in function to check string size
    $result .= $text[$c];
    $c++;
    if($c % $qt == 0){
        $result .= $nl;
    }
}

echo $result;

输出(<pre>显示已结算的数量):

Lorem ipsum dol
or sit amet, co
nsectetur adipi
scing elit. Mor
bi semper, est 
non gravida ven
enatis, est neq
ue fringilla qu
am, hendrerit u
ltrices justo t
urpis nec augue
.

在行动here中查看。

<小时/> 我这样做只是为了练习。你应该试试你的东西。人们不能为你“学习”逻辑。

答案 1 :(得分:0)

$number = 15;
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi semper, est non gravida venenatis, est neque fringilla quam, hendrerit ultrices justo turpis nec augue.';

简单的解决方案是简单地浏览每个角色,记录你所处的角色,然后在正确的位置输出换行符。

for ($i = 0, $l = strlen($text); $i < $l; $i++) {
    echo $text[$i];
    if ($i % $number === $number - 1) {
        echo "\n";
    }
}

另一种方法是弄清楚最终会有多少行然后相应地提取子串,然后再在正确的位置添加换行符:

$linesTotal = ceil(strlen($text) / $number);
for ($i = 0; $i < $linesTotal; $i++) {
    echo substr($text, $i * $number, $number);
    if ($i < $linesTotal - 1) {
        echo "\n";
    }
}

这将是更好的解决方案,但不在作业的参数范围内:

echo trim(chunk_split($text, $number));