Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I avoid trailing empty items being removed when splitting strings?

Tags:

ruby

I am doing:

"b::::c:::".split(':')

Result:

["b", "", "", "", "c", "", ""] # expect
["b", "", "", "", "c"] # actual

What is the problem here? how can i get what i expected.

like image 777
user612308 Avatar asked Mar 27 '11 22:03

user612308


People also ask

What happens if you split an empty string?

If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string. If you specify an empty string for string, the split() method will return an empty string and not an array of strings.

Can split return an empty array?

Using split()If the string and separator are both empty strings, an empty array is returned.

How to remove empty string from split?

To split a string and remove the empty elements from the array, call the split() method on the string to get an array of substrings and use the filter() method to filter out any empty elements from the array, e.g. str. split(' ').


1 Answers

There's a limit parameter to .split(pattern=$;, [limit]). If limit is omitted, trailing null fields are suppressed. You need to provide a negative limit

"b::::c:::".split(':', -1) 

but bear in mind that this will return three "" values at the end of the array.

result: ["b", "", "", "", "c", "", "", ""] 
like image 84
Russ Cam Avatar answered Oct 18 '22 14:10

Russ Cam