Strings in Elixir are delimited by double quotes, and they are encoded in UTF-8:
"Hi!"
Strings can be concatenated using the <>/2
operator:
"Welcome to" <> " " <> "New York"
# => "Welcome to New York"
Strings in Elixir support interpolation using the #{}
syntax:
"6 * 7 = #{6 * 7}"
# => "6 * 7 = 42"
To put a newline character in a string, use the \n
escape code:
"1\n2\n3\n"
To comfortably work with texts with a lot of newlines, use the triple-double-quote heredoc syntax instead:
"""
1
2
3
"""
Elixir provides many functions for working with strings in the String
module.
The |>
operator is called the pipe operator. It can be used to chain function calls together in such a way that the value returned by the previous function call is passed as the first argument to the next function call.
"hello"
|> String.upcase()
|> Kernel.<>("?!")
# => "HELLO?!"
In this exercise, you are going to help high school sweethearts profess their love on social media by generating an ASCII heart with their initials:
****** ******
** ** ** **
** ** ** **
** * **
** **
** J. K. + M. B. **
** **
** **
** **
** **
** **
** **
***
*
Implement the HighSchoolSweetheart.first_letter/1
function. It should take a name and return its first letter. It should clean up any unnecessary whitespace from the name.
HighSchoolSweetheart.first_letter("Jane")
# => "J"
Implement the HighSchoolSweetheart.initial/1
function. It should take a name and return its first letter, uppercase, followed by a dot. Make sure to reuse HighSchoolSweetheart.first_letter/1
that you defined in the previous step.
HighSchoolSweetheart.initial("Robert")
# => "R."
Implement the HighSchoolSweetheart.initials/1
function. It should take a full name, consisting of a first name and a last name separated by a space, and return the initials. Make sure to reuse HighSchoolSweetheart.initial/1
that you defined in the previous step.
HighSchoolSweetheart.initials("Lance Green")
# => "L. G."
Implement the HighSchoolSweetheart.pair/2
function. It should take two full names and return the initials inside an ASCII heart. Make sure to reuse HighSchoolSweetheart.initials/1
that you defined in the previous step.
HighSchoolSweetheart.pair("Blake Miller", "Riley Lewis")
# => """
# ****** ******
# ** ** ** **
# ** ** ** **
# ** * **
# ** **
# ** B. M. + R. L. **
# ** **
# ** **
# ** **
# ** **
# ** **
# ** **
# ***
# *
# """
Sign up to Exercism to learn and master Elixir with 57 concepts, 159 exercises, and real human mentoring, all for free.