7 January 2015

Quiz 76: Find all continuous substrings of all lengths

Problem:

Given a string, you have to all continuous substrings of different lengths
Ex for abc, print a,ab,abc,b,bc,c

Input Format: 

A String

Output Format: 

Different substrings in each line

Constraints: 
None

Sample Input

perl

Sample Output:

p
pe
per
perl
e
er
erl
r
rl
l

Explanations:

all continuous substrings of length 1 to 4


Solution:

use strict;
use warnings;

chomp(my $a=<STDIN>);
for (my $i=0; $i<=length($a);$i++) 
{
for (my $j = $i+1;$j<=length($a);$j++) 
{
        print substr($a, $i, $j - $i) . "\n";
}
}


Tips:

Length can give length of string directly

1 comment:

  1. try this (does produce answers in a different order) :

    echo perl | perl -lne '/.+(??{print$&})^/'

    ReplyDelete