If you are dealing with large strings then the following may be a little quicker than the regex based techniques posted so far:

use warnings; use strict; my $str; my $len = 0; while ($len < 1000000) { my $runLen = int rand (50); $str .= chr (ord ('a') + int rand (26)) x $runLen; $len += $runLen; } my $sstr = substr ($str, 0, 1) . (substr ($str, 1) ^ $str); my @bestRuns; my $match = "\0"; my $bestRunLen = 2; my $scan = 0; while (-1 != (my $start = index $sstr, $match, $scan)) { my $runLen = length ((substr ($sstr, $start) =~ /(\0+)/)[0]) + 1; if ($runLen > $bestRunLen) { # new best match @bestRuns = $start - 1; $bestRunLen = $runLen; $match = "\0" x ($bestRunLen - 1); } else { # another best match push @bestRuns, $start - 1; } $scan = $start + $bestRunLen - 1; } for (@bestRuns) { print "Run of " . substr ($str, $_, 1) . " from $_ for $bestRunLen +\n"; }

Prints:

Run of r from 766269 for 144

Note that this finds all the matches and their start indexes.


DWIM is Perl's answer to Gödel

In reply to Re: Longest possible run of a single character by GrandFather
in thread Longest possible run of a single character by srdst13

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.