in reply to Supress similar chars in the string

Without using the regex, you may traverse through each character one by one, remember the previous character pattern and the pattern count.
# suppose this is the input string my $str_in; # and this is the output my $str_out; my $char; my $char_count; my $len = length $str_in; for (my $i=0; $i<$len; $i++) { my $curr = substr $str_in,$i,1; if (!defined $char) { # initialize state $char = $curr; $char_count = 1; } else { if ($curr eq $char) { # current char is same with previous ones if ($char_count>=3) { $char_count++; } else { $str_out .= $curr; $char_count++; } } else { # we found a different char $char = $curr; $char_count = 1; $str_out .= $curr; } } }

Replies are listed 'Best First'.
Re^2: Supress similar chars in the string
by Jim (Curate) on Jan 19, 2011 at 02:13 UTC
    Without using the regex, you may traverse through each character one by one, remember the previous character pattern and the pattern count.

    You may, but why would you write such a custom, special-case state machine in Perl? This is precisely what regular expressions in scripting languages like Perl are for.

    $ echo '........ aaaaaaaasssssss __________ ++++++++++ ---------' | > perl -pe 's{(.)\1\1\K\1+}{}g' ... aaasss ___ +++ --- $

    That's unbeatably simple and elegant, don't you think?