Created
February 16, 2017 19:05
-
-
Save notriddle/421701a1e5edeed582a77ff0a7b50ac2 to your computer and use it in GitHub Desktop.
Split a string without using regex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Split do | |
@moduledoc """ | |
iex(2)> Split.split("this,is,1,way,to,do_it") | |
["this", "is", "1", "way", "to", "do", "it"] | |
""" | |
@spec split(bitstring) :: [bitstring] | |
def split(s) do | |
do_split(s, [], []) | |
|> Enum.map(&List.to_string/1) | |
|> Enum.map(&String.reverse/1) | |
|> Enum.reverse() | |
end | |
@spec do_split(bitstring, charlist, [charlist]) :: [charlist] | |
def do_split("", [], list) do | |
list | |
end | |
def do_split("", cur, list) do | |
[cur | list] | |
end | |
def do_split(<<hd :: rest>>, cur, list) when (hd >= 97 and hd <= 122) or (hd >= 48 and hd <= 57) do | |
do_split(rest, [hd | cur], list) | |
end | |
def do_split(<<_ :: rest>>, cur, list) do | |
do_split(rest, [], [cur | list]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment