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?
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.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
As the name suggests, a Java String Split() method is used to decompose or split the invoking Java String into parts and return the Array. Each part or item of an Array is delimited by the delimiters(“”, “ ”, \\) or regular expression that we have passed. The return type of Split is an Array of type Strings.
split() method accepts two arguments. The first optional argument is separator , which specifies what kind of separator to use for splitting the string. If this argument is not provided, the default value is any whitespace, meaning the string will split whenever .
Ruby's scan
is useful for this:
'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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With