Skip to content

Commit 64cdc76

Browse files
committed
Accept the trim option when splitting strings
By default `trim` will be set to true. Because `:binary.strip` only removes empty strings from the end of the result, we have to apply a filter to remove empty strings from the beginning before returning.
1 parent 34dade0 commit 64cdc76

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

lib/elixir/lib/string.ex

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -163,12 +163,17 @@ defmodule String do
163163
The string is split into as many parts as possible by
164164
default, unless the `global` option is set to `false`.
165165
166+
Empty strings are removed from the result, unless the
167+
`trim` option is set to `false`.
168+
166169
## Examples
167170
168171
iex> String.split("a,b,c", ",")
169172
["a", "b", "c"]
170173
iex> String.split("a,b,c", ",", global: false)
171174
["a", "b,c"]
175+
iex> String.split(" a b c ", " ", trim: false)
176+
["", "a", "b", "c", ""]
172177
173178
iex> String.split("1,2 3,4", [" ", ","])
174179
["1", "2", "3", "4"]
@@ -188,12 +193,19 @@ defmodule String do
188193
def split("", _pattern, _options), do: [""]
189194

190195
def split(binary, pattern, options) when is_regex(pattern) do
191-
Regex.split(pattern, binary, global: options[:global])
196+
Regex.split(pattern, binary, options)
192197
end
193198

194199
def split(binary, pattern, options) do
195-
opts = if options[:global] != false, do: [:global], else: []
196-
:binary.split(binary, pattern, opts)
200+
defaults = [global: true, trim: true]
201+
options = Keyword.merge(defaults, options)
202+
203+
option_keys = Enum.filter_map(options, &elem(&1, 1), &elem(&1, 0))
204+
splits = :binary.split(binary, pattern, option_keys)
205+
206+
if options[:trim], do: splits = Enum.filter(splits, &(&1 != ""))
207+
208+
splits
197209
end
198210

199211
@doc """

lib/elixir/test/elixir/string_test.exs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,13 @@ defmodule StringTest do
2929
assert String.split("a,b,c", ",") == ["a", "b", "c"]
3030
assert String.split("a,b", ".") == ["a,b"]
3131
assert String.split("1,2 3,4", [" ", ","]) == ["1", "2", "3", "4"]
32+
assert String.split(" a b c ", " ") == ["a", "b", "c"]
3233

3334
assert String.split("a,b,c", ",", global: false) == ["a", "b,c"]
3435
assert String.split("1,2 3,4", [" ", ","], global: false) == ["1", "2 3,4"]
36+
37+
assert String.split(" a b c ", " ", trim: false) == ["", "a", "b", "c", ""]
38+
assert String.split(" a b c ", " ", trim: false, global: false) == ["", "a b c "]
3539
end
3640

3741
test :split_with_regex do

0 commit comments

Comments
 (0)