Recipe 1.4 Processing a String One Character at a Time
1.4.1 Problem
You need to process
each character in a string individually.
1.4.2 Solution
Loop through each character in the string with
for. This example counts the vowels in a string:
$string = "This weekend, I'm going shopping for a pet chicken.";
$vowels = 0;
for ($i = 0, $j = strlen($string); $i < $j; $i++) {
if (strstr('aeiouAEIOU',$string[$i])) {
$vowels++;
}
}
1.4.3 Discussion
Processing a string a character at a time is an easy way to calculate
the "Look and
Say" sequence:
function lookandsay($s) {
// initialize the return value to the empty string
$r = '';
// $m holds the character we're counting, initialize to the first
* character in the string
$m = $s[0];
// $n is the number of $m's we've seen, initialize to 1
$n = 1;
for ($i = 1, $j = strlen($s); $i < $j; $i++) {
// if this character is the same as the last one
if ($s[$i] == $m) {
// increment the count of this character
$n++;
} else {
// otherwise, add the count and character to the return value //
$r .= $n.$m;
// set the character we're looking for to the current one //
$m = $s[$i];
// and reset the count to 1 //
$n = 1;
}
}
// return the built up string as well as the last count and character //
return $r.$n.$m;
}
for ($i = 0, $s = 1; $i < 10; $i++) {
$s = lookandsay($s);
print "$s\n";
}
1
11
21
1211
111221
312211
13112221
1113213211
31131211131221
13211311123113112211
It's called the "Look and
Say" sequence because each element is what you get
by looking at the previous element and saying what's
in it. For example, looking at the first element, 1, you say
"one one." So the second element is
"11." That's two
ones, so the third element is "21."
Similarly, that's one two and one one, so the fourth
element is "1211," and so on.
1.4.4 See Also
Documentation on for at
http://www.php.net/for; more about the
"Look and Say" sequence at
http://mathworld.wolfram.com/LookandSaySequence.html.
|