如何将字符串拆分为多个单词的数组?

时间:2022-04-08 21:36:50

I have a string that I'm using .split(' ') on to split up the string into an array of words. Can I use a similar method to split the string into an array of 2 words instead?

我有一个字符串,我正在使用.split('')将字符串拆分为一个单词数组。我可以使用类似的方法将字符串拆分为2个字的数组吗?

Returns an array where each element is one word:

返回一个数组,其中每个元素都是一个单词:

words = string.split(' ')

I'm looking to return an array where each element is 2 words instead.

我想返回一个数组,其中每个元素是2个单词。

5 个解决方案

#1


7  

str = 'one two three four five six seven'
str.split.each_slice(2).map{|a|a.join ' '}
=> ["one two", "three four", "five six", "seven"]

This also handles the case of an odd number of words.

这也处理奇数个字的情况。

#2


4  

You can do

你可以做

string= 'one1! two2@ three3# four4$ five5% six6^ sev'
string.scan(/\S+ ?\S*/)
# => ["one1! two2@", "three3# four4$", "five5% six6^", "sev"]

#3


3  

Something like this should work:

像这样的东西应该工作:

string.scan(/\w+ \w+/)

#4


2  

Ruby's scan is useful for this:

Ruby的扫描对此非常有用:

'a b c'.scan(/\w+(?:\s+\w+)?/)
=> ["a b", "c"]

'a b c d e f g'.scan(/\w+(?:\s+\w+)?/)
=> ["a b", "c d", "e f", "g"]

#5


2  

This is all I had to do:

这就是我必须做的一切:

def first_word
    chat = "I love Ruby"
    chat = chat.split(" ")
    chat[0]
end

#1


7  

str = 'one two three four five six seven'
str.split.each_slice(2).map{|a|a.join ' '}
=> ["one two", "three four", "five six", "seven"]

This also handles the case of an odd number of words.

这也处理奇数个字的情况。

#2


4  

You can do

你可以做

string= 'one1! two2@ three3# four4$ five5% six6^ sev'
string.scan(/\S+ ?\S*/)
# => ["one1! two2@", "three3# four4$", "five5% six6^", "sev"]

#3


3  

Something like this should work:

像这样的东西应该工作:

string.scan(/\w+ \w+/)

#4


2  

Ruby's scan is useful for this:

Ruby的扫描对此非常有用:

'a b c'.scan(/\w+(?:\s+\w+)?/)
=> ["a b", "c"]

'a b c d e f g'.scan(/\w+(?:\s+\w+)?/)
=> ["a b", "c d", "e f", "g"]

#5


2  

This is all I had to do:

这就是我必须做的一切:

def first_word
    chat = "I love Ruby"
    chat = chat.split(" ")
    chat[0]
end