Skip to content

Instantly share code, notes, and snippets.

@notriddle
Created February 16, 2017 19:05
Show Gist options
  • Save notriddle/421701a1e5edeed582a77ff0a7b50ac2 to your computer and use it in GitHub Desktop.
Save notriddle/421701a1e5edeed582a77ff0a7b50ac2 to your computer and use it in GitHub Desktop.
Split a string without using regex
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