Q:

Write a PHP program to count a substring of length 2 appears in a given string and also as the last 2 characters of the string

0

Write a PHP program to count a substring of length 2 appears in a given string and also as the last 2 characters of the string. Do not count the end substring

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

<?php
function test($s)
{
    $last_two_char = substr($s, strlen($s)-2, 2);
    $ctr = 0;

    for ($i = 0; $i < strlen($s)-2; $i++)
        {
           if (substr($s, $i, 2) == $last_two_char) 
           $ctr = $ctr +1;
        }
    return $ctr;
 }

echo test("abcdsab")."\n";
echo test("abcdabab")."\n";
echo test("abcabdabab")."\n";
echo test("abcabd")."\n";

Sample Output:

1
2
3
0

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now