【问题标题】:How to split a sentence into multiple parts in Ruby如何在Ruby中将一个句子分成多个部分
【发布时间】:2017-11-17 09:55:25
【问题描述】:

我想拆分一个主字符串,并用在 Ruby 中获得的单词创建多个字符串。

str = "one two three four five"

我想在一个字符串数组中创建所有这些可能性:

"one"
"one two"
"one two three"
"one two three four" 
"one two three four five" 

还有:

"two three four five"
"three four five"
"four five"
"five"

理想情况下,我也会获得里面的字符串,但不是必需的:

"two three four"
"two three"
"three four"

我尝试了很多东西,但很难找到最好的方法。

例如,我尝试使用 each_slice:

words = string.split(" ")
        number_of_words = words.length
        max_number_of_slices = number_of_words
        array_of_strings_to_match = []
        number_of_slices = 1
        while (number_of_slices <= max_number_of_slices)
          array = words.each_slice(number_of_slices).map do |a| a.join ' ' end
          array.each do |w| array_of_strings_to_match << w end
          number_of_slices = number_of_slices + 1
        end

但这不是好方法。

欢迎任何想法。 :-)

这个问题和this one有点不一样,因为我需要的是一个单词的句子,而不是一个字母的字符串(即使完全一样)。

【问题讨论】:

标签: ruby string split


【解决方案1】:
str = "one two three four five".split
1.upto(str.size).flat_map { |i| str.each_cons(i).to_a }

#⇒ [["one"], ["two"], ["three"], ["four"], ["five"],
#   ["one", "two"], ["two", "three"], ["three", "four"], ["four", "five"],
#   ["one", "two", "three"], ["two", "three", "four"], ["three", "four", "five"],
#   ["one", "two", "three", "four"], ["two", "three", "four", "five"], 
#   ["one", "two", "three", "four", "five"]]

【讨论】:

  • 这实际上是我修改过的更好的解决方案。 +1
  • 这是一个优雅的解决方案!谢谢。
【解决方案2】:

基于this answer的修改版本:

def split_words(string)
  words = string.split
  (0..words.length).inject([]) do |ai,i|
    (1..words.length - i).inject(ai) { |aj,j| aj << words[i,j] }
  end.map { |words| words.join(' ') }.uniq
end

用法

str = "one two three four five"

split_words(str)
#=> ["one",
#    "one two",
#    "one two three",
#    "one two three four",
#    "one two three four five",
#    "two",
#    "two three",
#    "two three four",
#    "two three four five",
#    "three",
#    "three four",
#    "three four five",
#    "four",
#    "four five",
#    "five"]

【讨论】:

  • 感谢汤姆的这个修改版本。我没有匹配引用的帖子。我会接受 mudasobwa 的其他解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
  • 2018-04-26
  • 2023-02-10
  • 1970-01-01
相关资源
最近更新 更多