【发布时间】:2012-01-21 09:03:40
【问题描述】:
我想从字符串中的以下单词中获取字符数。例如,如果我的输入是I am John,那么输出必须是这样的:
1 // count of 'I'
4 // count of 'I am'
9 // count of 'I am John'
我在 PHP 中使用这样的代码来处理这个过程:
$string = 'I am John';
$words = explode(' ',$string);
$count_words = count($words);
$i =0;
while ($i<=$count_words){
$word_length =0;
$k=0;
while($k<=$i){
$word_length = strlen($words[$k-1]);
$word_length = $word_length + strlen($words[$k]);
$k++;
}
$word_length = $word_length + $i; // there is "$i" means "space"
echo $word_length.'<br/>';
$i++;
}
但它会像这样返回输出:
1
4
8
7
为什么?我的错误在哪里?我的代码必须是什么样的?
提前致谢!
【问题讨论】:
-
Re title: 不,您不仅在迄今为止最流行的语言之一的最基本、广泛使用的语言结构中发现了一个错误。 :o)
-
ok :) 你建议什么标题? :)
-
这是一个免费赠品:codepad.viper-7.com/3R02TK 但说真的,要学会调试自己的代码,否则你将无法在编程中完成任何工作。调试只是意味着逐步检查代码以找出问题所在。经常使用
var_dump()。
标签: php algorithm loops while-loop