我实现此目标的一种方法是: def get_all_word_combinations(str,min_length)字符= str.split('')all_results = [](min_length..str.size).每个| x |chars.each_cons(x)做| r |all_results<<加入结尾结尾返回all_results结尾 但是不确定这是否可以用较大的单词来表达.解决方案此解决方案避免了不必要的 joins : word ="hello"大小= word.sizemin_size = 3(min_size..size).flat_map {| l |(0..size-l).map {| i |词[i,l]}}#=>["hel","ell","llo","hell","ello","hello"] 如果您不需要数组,而只需要遍历每个可能的子字符串,则此解决方案将使用更少的内存: (min_size..size).each | l |(0..size-l).each做| i |#用单词[i,l]做点什么结尾结尾 I want to generate all possible consecutive word combinations of a particular string, given a minimum length as an arg.So say I have "hello", the result would be (given a min length of 3): 'hel', 'ell', 'llo', 'hell', 'ello', 'hello'.One way I've achieve this is via:def get_all_word_combinations(str, min_length) chars = str.split('') all_results = [] (min_length..str.size).each do |x| chars.each_cons(x) do |r| all_results << r.join end end return all_results endBut not sure if this would work with bigger words. 解决方案 This solution avoids unnecessary joins :word = "hello"size = word.sizemin_size = 3(min_size..size).flat_map { |l| (0..size - l).map { |i| word[i, l] } }#=> ["hel", "ell", "llo", "hell", "ello", "hello"]If you don't need an Array but just need to iterate over every possible substring, this solution will use less memory :(min_size..size).each do |l| (0..size - l).each do |i| # do something with word[i, l] endend 这篇关于生成字符串的所有可能的连续单词组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-11 16:43