🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir String Functions

String functions are named helpers that change text or answer questions about it. Each function takes the string first and returns a new string or another value.

Change case and clean text

Case and cleaning functions return cleaned-up copies. The replace call swaps every matching word.

IO.puts(String.upcase("hello"))
IO.puts(String.downcase("LOUD"))
IO.puts(String.trim("  padded  "))
IO.puts(String.replace("cat and cat", "cat", "dog"))

Check and pick parts of a string

contains? checks for a smaller string inside a bigger one. at picks one character by position, slice picks a run, and reverse flips the whole string.

text = "pineapple"
IO.puts(String.contains?(text, "apple"))
IO.puts(String.at(text, 0))
IO.puts(String.slice(text, 4, 5))
IO.puts(String.reverse(text))

Split, pad and list characters

split breaks text into a list of parts, by spaces or by a separator you name. pad_leading stretches short text to a set width, and codepoints lists the single characters.

IO.inspect(String.split("one two three"))
IO.inspect(String.split("a,b,c", ","))
IO.puts(String.pad_leading("7", 3, "0"))
IO.inspect(String.codepoints("abc"))

Example

label = "  item 42  "
clean = String.trim(label)
IO.puts(String.upcase(clean))
IO.puts(String.to_integer("42"))
IO.inspect(Integer.parse("42"))
IO.inspect(Float.parse("3.5"))
IO.puts(String.pad_leading("9", 2, "0"))

Key points

  • Case: String.upcase makes all letters capital, and String.downcase makes them small.
  • Cleaning: String.trim removes spaces from both ends of a string.
  • Changing text: String.replace swaps every match for new text.
  • Checking text: String.contains? tells whether one string sits inside another.
  • Picking parts: String.at returns one character, and String.slice returns a run of characters given a start and a length.
  • Parsing: String.to_integer turns digit text into an integer, and Integer.parse also reports any leftover text.

In this example, trim cleans the label and upcase prints it in capitals. String.to_integer reads the digits as 42, the two parse calls return the number with an empty leftover, and pad_leading stretches 9 into 09.

Note

string functions return new values and never change the original string.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does String.slice("hello", 1, 3) return?