16 Jul 2013, 02:16
Dave_gnome_head_isolated_pragsmall

Dave Thomas (338 posts)

  • Write a function to capitalize the sentences in a string. Each sentence is terminated by a period and a space. Right now, the case of the characters in the string is random.

    iex> capitalize_sentences("oh. a DOG. woof. ")
    "Oh. A dog. Woof. "
    
A Possible Solution
defmodule MyString do

  def capitalize_sentences(string) do
    string
    |> String.split(%r{\.\s+})
    |> Enum.map(String.capitalize(&1))
    |> Enum.join(". ")
  end

end

IO.inspect MyString.capitalize_sentences("oh. a DOG. woof. ") 
07 Jan 2014, 00:59
Generic-user-small

Eric Liaw (3 posts)

irc chat discussion noted a fix for this should have a & in front of the String.capitalize, so it would instead be:

  def capitalize_sentences(string) do
    string
    |> String.split(%r{\.\s+})
    |> Enum.map(&String.capitalize(&1))
    |> Enum.join(". ")
  end
21 Jun 2014, 01:35
Generic-user-small

Luke Imhoff (6 posts)

You can get rid of the argument to Enum.join with a slightly more complex regex as I used in my solution:

defmodule Sentences do
  def captialize_sentences(string) do
    String.split(string, ~r{(?<=\. )(?=.)})
    |> Enum.map(&String.capitalize/1)
    |> Enum.join
  end
end

The regex does a look behind (?<=) for \. and then I had to add a look ahead (?=) for any character ., so that I didn’t get an empty final string after “woof. “.

  You must be logged in to comment