在C ++中,我可以在最后添加一个空字符来区分单词。但我不知道如何在Ruby中 我不想使用拼接方法。以下是我正在进行的工作。
i = 0
split_array = []
while (i<sentence.length)
puts (sentence.length)
if (i+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"]