To get all possible K length substrings in a string in Ruby, you can use a loop to iterate through the string and extract substrings of the desired length.
In this example,
str
with a value of "Hello World"
using the assignment operator `=`.k
and assign it the value `3`, representing the length of substrings we want to extract.substrings
to store the extracted substrings.i
ranging from `0` to `str.length - k`. This loop iterates through the string, stopping when there are fewer than k
characters left to extract a substring.i
and of length k
. Append this substring to the substrings
array using the `<<` operator.substrings
array using the `puts` method to display all the extracted substrings.str = "Hello World"
k = 3
substrings = []
for i in 0..(str.length - k)
substrings << str[i, k]
end
puts "All #{k}-length substrings: #{substrings}"
All 3-length substrings: ["Hel", "ell", "llo", "lo ", "o W", " Wo", "Wor", "orl", "rld"]
In this example,
str
with a value of "apple"
using the assignment operator `=`.k
and assign it the value `2`, representing the length of substrings we want to extract.substrings
to store the extracted substrings.i
ranging from `0` to `str.length - k`. This loop iterates through the string, stopping when there are fewer than k
characters left to extract a substring.i
and of length k
. Append this substring to the substrings
array using the `<<` operator.substrings
array using the `puts` method to display all the extracted substrings.str = "apple"
k = 2
substrings = []
for i in 0..(str.length - k)
substrings << str[i, k]
end
puts "All #{k}-length substrings: #{substrings}"
All 2-length substrings: ["ap", "pp", "pl", "le"]
In this tutorial, we learned How to get all the possible K length Substrings in a String in Ruby language with well detailed examples.