# substrings

Discussion in 'Ruby' started by Ed Redman, Jan 19, 2006.

1. ### Ed RedmanGuest

I am struggling with the following.
Given a sting of a given length example string = 'bkerhcno'
give all the subsets of string of length 4

I don't need all the permutations just the subsets.
I can use the slice method to give me some subsets i.e
s1 = string.slice(0,4)
s2 = string.slice(1,4) etc.
Just how do I generate all the possible combination of 4 characters.

By analagy, would like to extend to finding all combination of length 5,6,
and 7.

Hope someone can help.

Ed Redman, Jan 19, 2006

2. ### Robert KlemmeGuest

Ed Redman wrote:
> I am struggling with the following.
> Given a sting of a given length example string = 'bkerhcno'
> give all the subsets of string of length 4
>
> I don't need all the permutations just the subsets.
> I can use the slice method to give me some subsets i.e
> s1 = string.slice(0,4)
> s2 = string.slice(1,4) etc.
> Just how do I generate all the possible combination of 4 characters.
>
> By analagy, would like to extend to finding all combination of length
> 5,6, and 7.
>
> Hope someone can help.

def sub_strings(s,len)
(s.length - len).times do |idx|
yield s[idx,len]
end
end

>> sub_strings( 'bkerhcno', 4 ) {|s| p s}

"bker"
"kerh"
"erhc"
"rhcn"
"hcno"
=> 0..4

Kind regards

robert

Robert Klemme, Jan 19, 2006