仅使用while循环将句子分成单词

时间:2015-07-13 22:34:29

标签: ruby

在C ++中,我可以在最后添加一个空字符来区分单词。但我不知道如何在Ruby中 我不想使用拼接方法。以下是我正在进行的工作。

i = 0
    split_array = []
    while (i<sentence.length)
        puts (sentence.length)
        if (i+1 == " ")

1 个答案:

答案 0 :(得分:0)

另一种方式(无视标点和案例):

sentence = "the quick brown dog\njumped   over the lazy fox"

start_ndx = sentence.index(/\w/)
return [] if start_ndx.nil?
words = []
while start_ndx
  end_ndx = sentence.index(/\w\b/, start_ndx)
  words << sentence[start_ndx..end_ndx]
  start_ndx = sentence.index(/\w/, end_ndx+1)
end
words
  #=> ["the", "quick", "brown", "dog", "jumped", "over", "the", "lazy", "fox"]