String

Introduction #

A String in Elixir is a UTF-8 encoded binary.

Codepoints and graphemes

The functions in this module act according to the Unicode Standard, version 6.3.0.As per the standard, a codepoint is an Unicode Character, which may be represented by one or more bytes. For example, the character "é" is represented with two bytes:

iex> byte_size("é")
2

However, this module returns the proper length:

iex> String.length("é")
1

Furthermore, this module also presents the concept of graphemes, which are multiple characters that may be "perceived as a single character" by readers. For example, the same "é" character written above could be represented by the letter "e" followed by the accent ́:

iex> string = "\x{0065}\x{0301}"
iex> byte_size(string)
3
iex> String.length(string)
1

Although the example above is made of two characters, it is perceived by users as one.

Graphemes can also be two characters that are interpreted as one by some languages. For example, some languages may consider "ch" as a grapheme. However, since this information depends on the locale, it is not taken into account by this module.

In general, the functions in this module rely on the Unicode Standard, but does not contain any of the locale specific behaviour.

More information about graphemes can be found in the Unicode Standard Annex #29. This current Elixir version implements Extended Grapheme Cluster algorithm.

String and binary operations

To act accordingly to the Unicode Standard, many functions in this module runs in linear time, as it needs to traverse the whole string considering the proper Unicode codepoints.

For example, String.length/1 is going to take longer as the input grows. On the other hand, byte_size/1 always runs in constant time (i.e. regardless of the input size).

This means often there are performance costs in using the functions in this module, compared to the more low-level operations that work directly with binaries:

There are many situations where using the String module can be avoided in favor of binary functions or pattern matching. For example, imagine you have a string prefix and you want to remove this prefix from another string named full.

One may be tempted to write:

iex> take_prefix = fn full, prefix ->
...>   base = String.length(prefix)
...>   String.slice(full, base, String.length(full) - base)
...> end
...> take_prefix.("Mr. John", "Mr. ")
"John"

Although the function above works, it performs poorly. To calculate the length of the string, we need to traverse it fully, so we traverse both prefix and full strings, then slice the full one, traversing it again.

A first attempting at improving it could be with ranges:

iex> take_prefix = fn full, prefix ->
...>   base = String.length(prefix)
...>   String.slice(full, base..-1)
...> end
...> take_prefix.("Mr. John", "Mr. ")
"John"

While this is much better (we don't traverse full twice), it could still be improved. In this case, since we want to extract a substring from a string, we can use byte_size/1 and binary_part/3 as there is no chance we will slice in the middle of a codepoint made of more than one byte:

iex> take_prefix = fn full, prefix ->
...>   base = byte_size(prefix)
...>   binary_part(full, base, byte_size(full) - base)
...> end
...> take_prefix.("Mr. John", "Mr. ")
"John"

Or simply used pattern matching:

iex> take_prefix = fn full, prefix ->
...>   base = byte_size(prefix)
...>   <<_ :: binary-size(base), rest :: binary>> = full
...>   rest
...> end
...> take_prefix.("Mr. John", "Mr. ")
"John"

On the other hand, if you want to dynamically slice a string based on an integer value, then using String.slice/3 is the best option as it guarantees we won't incorrectly split a valid codepoint in multiple bytes.

Integer codepoints

Although codepoints could be represented as integers, this module represents all codepoints as strings. For example:

iex> String.codepoints("olá")
["o", "l", "á"]

There are a couple of ways to retrieve a character integer codepoint. One may use the ? construct:

iex> ?o
111

iex> ?á
225

Or also via pattern matching:

iex> << eacute :: utf8 >> = "á"
iex> eacute
225

As we have seen above, codepoints can be inserted into a string by their hexadecimal code:

"ol\x{0061}\x{0301}" #=>
"olá"

Self-synchronization

The UTF-8 encoding is self-synchronizing. This means that if malformed data (i.e., data that is not possible according to the definition of the encoding) is encountered, only one codepoint needs to be rejected.

This module relies on this behaviour to ignore such invalid characters. For example, length/1 is going to return a correct result even if an invalid codepoint is fed into it.

In other words, this module expects invalid data to be detected when retrieving data from the external source. For example, a driver that reads strings from a database will be the one responsible to check the validity of the encoding.

Source

Types #

t :: binary

grapheme :: t

Functions #

at(string, position)

Specs

Returns the grapheme in the position of the given utf8 string. If position is greater than string length, then it returns nil.

Examples

iex> String.at("elixir", 0)
"e"

iex> String.at("elixir", 1)
"l"

iex> String.at("elixir", 10)
nil

iex> String.at("elixir", -1)
"r"

iex> String.at("elixir", -10)
nil

capitalize(string)

Specs

  • capitalize(t) :: t

Converts the first character in the given string to uppercase and the remaining to lowercase.

This relies on the titlecase information provided by the Unicode Standard. Note this function makes no attempt to capitalize all words in the string (usually known as titlecase).

Examples

iex> String.capitalize("abcd")
"Abcd"

iex> String.capitalize("fin")
"Fin"

iex> String.capitalize("olá")
"Olá"

chunk(string, trait)

Specs

  • chunk(t, :valid | :printable) :: [t]

Splits the string into chunks of characters that share a common trait.

The trait can be one of two options:

  • :valid – the string is split into chunks of valid and invalid character sequences

  • :printable – the string is split into chunks of printable and non-printable character sequences

Returns a list of binaries each of which contains only one kind of characters.

If the given string is empty, an empty list is returned.

Examples

iex> String.chunk(<<?a, ?b, ?c, 0>>, :valid)
["abc\0"]

iex> String.chunk(<<?a, ?b, ?c, 0, 0x0ffff::utf8>>, :valid)
["abc\0", <<0x0ffff::utf8>>]

iex> String.chunk(<<?a, ?b, ?c, 0, 0x0ffff::utf8>>, :printable)
["abc", <<0, 0x0ffff::utf8>>]

codepoints(string)

Specs

Returns all codepoints in the string.

Examples

iex> String.codepoints("olá")
["o", "l", "á"]

iex> String.codepoints("оптими зации")
["о","п","т","и","м","и"," ","з","а","ц","и","и"]

iex> String.codepoints("ἅἪῼ")
["ἅ","Ἢ","ῼ"]

contains?(string, contents)

Specs

  • contains?(t, t | [t]) :: boolean

Check if string contains any of the given contents.

matches can be either a single string or a list of strings.

Examples

iex> String.contains? "elixir of life", "of"
true

iex> String.contains? "elixir of life", ["life", "death"]
true

iex> String.contains? "elixir of life", ["death", "mercury"]
false

downcase(binary)

Specs

  • downcase(t) :: t

Convert all characters on the given string to lowercase.

Examples

iex> String.downcase("ABCD")
"abcd"

iex> String.downcase("AB 123 XPTO")
"ab 123 xpto"

iex> String.downcase("OLÁ")
"olá"

duplicate(subject, n)

Specs

  • duplicate(t, pos_integer) :: t

Returns a binary subject duplicated n times.

Examples

iex> String.duplicate("abc", 0)
""

iex> String.duplicate("abc", 1)
"abc"

iex> String.duplicate("abc", 2)
"abcabc"

ends_with?(string, suffixes)

Specs

  • ends_with?(t, t | [t]) :: boolean

Returns true if string ends with any of the suffixes given, otherwise false. suffixes can be either a single suffix or a list of suffixes.

Examples

iex> String.ends_with? "language", "age"
true

iex> String.ends_with? "language", ["youth", "age"]
true

iex> String.ends_with? "language", ["youth", "elixir"]
false

first(string)

Specs

Returns the first grapheme from an utf8 string, nil if the string is empty.

Examples

iex> String.first("elixir")
"e"

iex> String.first("եոգլի")
"ե"

graphemes(string)

Specs

Returns unicode graphemes in the string as per Extended Grapheme Cluster algorithm outlined in the Unicode Standard Annex #29, Unicode Text Segmentation.

Examples

iex> String.graphemes("Ā̀stute")
["Ā̀","s","t","u","t","e"]

last(string)

Specs

Returns the last grapheme from an utf8 string, nil if the string is empty.

Examples

iex> String.last("elixir")
"r"

iex> String.last("եոգլի")
"ի"

length(string)

Specs

  • length(t) :: non_neg_integer

Returns the number of unicode graphemes in an utf8 string.

Examples

iex> String.length("elixir")
6

iex> String.length("եոգլի")
5

ljust(subject, len)

Specs

  • ljust(t, pos_integer) :: t

Returns a new string of length len with subject left justified and padded with padding. If padding is not present, it defaults to whitespace. When len is less than the length of subject, subject is returned.

Examples

iex> String.ljust("abc", 5)
"abc  "

iex> String.ljust("abc", 5, ?-)
"abc--"

ljust(subject, len, padding)

Specs

  • ljust(t, pos_integer, char) :: t

lstrip(binary)

Returns a string where leading Unicode whitespace has been removed.

Examples

iex> String.lstrip("   abc  ")
"abc  "

lstrip(other, char)

Specs

  • lstrip(t, char) :: t

Returns a string where leading char have been removed.

Examples

iex> String.lstrip("_  abc  _", ?_)
"  abc  _"

match?(string, regex)

Specs

Check if string matches the given regular expression.

Examples

iex> String.match?("foo", ~r/foo/)
true

iex> String.match?("bar", ~r/foo/)
false

next_codepoint(string)

Specs

Returns the next codepoint in a String.

The result is a tuple with the codepoint and the remaining of the string or nil in case the string reached its end.

As with other functions in the String module, this function does not check for the validity of the codepoint. That said, if an invalid codepoint is found, it will be returned by this function.

Examples

iex> String.next_codepoint("olá")
{"o", "lá"}

next_grapheme(string)

Specs

Returns the next grapheme in a String.

The result is a tuple with the grapheme and the remaining of the string or nil in case the String reached its end.

Examples

iex> String.next_grapheme("olá")
{"o", "lá"}

printable?(b)

Specs

  • printable?(t) :: boolean

Checks if a string is printable considering it is encoded as UTF-8. Returns true if so, false otherwise.

Examples

iex> String.printable?("abc")
true

replace(subject, pattern, replacement, options \\ [])

Specs

Returns a new binary based on subject by replacing the parts matching pattern by replacement. By default, it replaces all entries, except if the global option is set to false.

A pattern may be a string or a regex.

Examples

iex> String.replace("a,b,c", ",", "-")
"a-b-c"

iex> String.replace("a,b,c", ",", "-", global: false)
"a-b,c"

The pattern can also be a regex. In those cases, one can give \N in the replacement string to access a specific capture in the regex:

iex> String.replace("a,b,c", ~r/,(.)/, ",\\1\\1")
"a,bb,cc"

Notice we had to escape the escape character \. By giving &, one can inject the whole matched pattern in the replacement string.

When strings are used as a pattern, a developer can also use the replaced part inside the replacement via the :insert_replaced option:

iex> String.replace("a,b,c", "b", "[]", insert_replaced: 1)
"a,[b],c"

iex> String.replace("a,b,c", ",", "[]", insert_replaced: 2)
"a[],b[],c"

iex> String.replace("a,b,c", ",", "[]", insert_replaced: [1, 1])
"a[,,]b[,,]c"

reverse(string)

Specs

  • reverse(t) :: t

Reverses the given string. Works on graphemes.

Examples

iex> String.reverse("abcd")
"dcba"

iex> String.reverse("hello world")
"dlrow olleh"

iex> String.reverse("hello ∂og")
"go∂ olleh"

rjust(subject, len)

Specs

  • rjust(t, pos_integer) :: t

Returns a new string of length len with subject right justified and padded with padding. If padding is not present, it defaults to whitespace. When len is less than the length of subject, subject is returned.

Examples

iex> String.rjust("abc", 5)
"  abc"

iex> String.rjust("abc", 5, ?-)
"--abc"

rjust(subject, len, padding)

Specs

  • rjust(t, pos_integer, char) :: t

rstrip(binary)

Specs

  • rstrip(t) :: t

Returns a string where trailing Unicode whitespace has been removed.

Examples

iex> String.rstrip("   abc  ")
"   abc"

rstrip(string, char)

Specs

  • rstrip(t, char) :: t

Returns a string where trailing char have been removed.

Examples

iex> String.rstrip("   abc _", ?_)
"   abc "

slice(string, range)

Specs

Returns a substring from the offset given by the start of the range to the offset given by the end of the range.

If the start of the range is not a valid offset for the given string or if the range is in reverse order, returns "".

If the start or end of the range are negative, the whole string is traversed first in order to convert the negative indexes into positive ones.

Remember this function works with unicode codepoints and consider the slices to represent codepoints offsets. If you want to split on raw bytes, check Kernel.binary_part/3 instead.

Examples

iex> String.slice("elixir", 1..3)
"lix"

iex> String.slice("elixir", 1..10)
"lixir"

iex> String.slice("elixir", 10..3)
""

iex> String.slice("elixir", -4..-1)
"ixir"

iex> String.slice("elixir", 2..-1)
"ixir"

iex> String.slice("elixir", -4..6)
"ixir"

iex> String.slice("elixir", -1..-4)
""

iex> String.slice("elixir", -10..-7)
""

iex> String.slice("a", 0..1500)
"a"

iex> String.slice("a", 1..1500)
""

slice(string, start, len)

Specs

Returns a substring starting at the offset given by the first, and a length given by the second.

If the offset is greater than string length, then it returns "".

Remember this function works with unicode codepoints and consider the slices to represent codepoints offsets. If you want to split on raw bytes, check Kernel.binary_part/3 instead.

Examples

iex> String.slice("elixir", 1, 3)
"lix"

iex> String.slice("elixir", 1, 10)
"lixir"

iex> String.slice("elixir", 10, 3)
""

iex> String.slice("elixir", -4, 4)
"ixir"

iex> String.slice("elixir", -10, 3)
""

iex> String.slice("a", 0, 1500)
"a"

iex> String.slice("a", 1, 1500)
""

iex> String.slice("a", 2, 1500)
""

split(binary)

Specs

  • split(t) :: [t]

Divides a string into substrings at each Unicode whitespace occurrence with leading and trailing whitespace ignored.

Examples

iex> String.split("foo bar")
["foo", "bar"]

iex> String.split("foo" <> <<194, 133>> <> "bar")
["foo", "bar"]

iex> String.split(" foo bar ")
["foo", "bar"]

split(string, pattern, options \\ [])

Specs

Divides a string into substrings based on a pattern.

Returns a list of these substrings. The pattern can be a string, a list of strings or a regular expression.

The string is split into as many parts as possible by default, but can be controlled via the parts: num option. If you pass parts: :infinity, it will return all possible parts.

Empty strings are only removed from the result if the trim option is set to true.

Examples

Splitting with a string pattern:

iex> String.split("a,b,c", ",")
["a", "b", "c"]

iex> String.split("a,b,c", ",", parts: 2)
["a", "b,c"]

iex> String.split(" a b c ", " ", trim: true)
["a", "b", "c"]

A list of patterns:

iex> String.split("1,2 3,4", [" ", ","])
["1", "2", "3", "4"]

A regular expression:

iex> String.split("a,b,c", ~r{,})
["a", "b", "c"]

iex> String.split("a,b,c", ~r{,}, parts: 2)
["a", "b,c"]

iex> String.split(" a b c ", ~r{\s}, trim: true)
["a", "b", "c"]

Splitting on empty patterns returns codepoints:

iex> String.split("abc", ~r{})
["a", "b", "c", ""]

iex> String.split("abc", "")
["a", "b", "c", ""]

iex> String.split("abc", "", trim: true)
["a", "b", "c"]

iex> String.split("abc", "", parts: 2)
["a", "bc"]

split_at(string, offset)

Specs

  • split_at(t, integer) :: {t, t}

Splits a string into two at the specified offset. When the offset given is negative, location is counted from the end of the string.

The offset is capped to the length of the string.

Returns a tuple with two elements.

Examples

iex> String.split_at "sweetelixir", 5
{"sweet", "elixir"}

iex> String.split_at "sweetelixir", -6
{"sweet", "elixir"}

iex> String.split_at "abc", 0
{"", "abc"}

iex> String.split_at "abc", 1000
{"abc", ""}

iex> String.split_at "abc", -1000
{"", "abc"}

starts_with?(string, prefixes)

Specs

  • starts_with?(t, t | [t]) :: boolean

Returns true if string starts with any of the prefixes given, otherwise false. prefixes can be either a single prefix or a list of prefixes.

Examples

iex> String.starts_with? "elixir", "eli"
true

iex> String.starts_with? "elixir", ["erlang", "elixir"]
true

iex> String.starts_with? "elixir", ["erlang", "ruby"]
false

strip(string)

Specs

  • strip(t) :: t

Returns a string where leading/trailing Unicode whitespace has been removed.

Examples

iex> String.strip("   abc  ")
"abc"

strip(string, char)

Specs

  • strip(t, char) :: t

Returns a string where leading/trailing char have been removed.

Examples

iex> String.strip("a  abc  a", ?a)
"  abc  "

to_atom(string)

Specs

Converts a string to an atom.

Currently Elixir does not support conversions from strings which contains Unicode codepoints greater than 0xFF.

Inlined by the compiler.

Examples

iex> String.to_atom("my_atom")
:my_atom

to_char_list(string)

Specs

  • to_char_list(t) :: char_list

Converts a string into a char list.

Examples

iex> String.to_char_list("æß")
'æß'

Notice that this function expect a list of integer representing UTF-8 codepoints. If you have a raw binary, you must instead use the :binary module.

to_existing_atom(string)

Specs

Converts a string to an existing atom.

Currently Elixir does not support conversions from strings which contains Unicode codepoints greater than 0xFF.

Inlined by the compiler.

Examples

iex> :my_atom
iex> String.to_existing_atom("my_atom")
:my_atom

iex> String.to_existing_atom("this_atom_will_never_exist")
** (ArgumentError) argument error

to_float(string)

Specs

Returns a float whose text representation is string.

Inlined by the compiler.

Examples

iex> String.to_float("2.2017764e+0")
2.2017764

to_integer(string)

Specs

Returns a integer whose text representation is string.

Inlined by the compiler.

Examples

iex> String.to_integer("123")
123

to_integer(string, base)

Specs

  • to_integer(String.t, pos_integer) :: integer

Returns an integer whose text representation is string in base base.

Inlined by the compiler.

Examples

iex> String.to_integer("3FF", 16)
1023

upcase(binary)

Specs

  • upcase(t) :: t

Convert all characters on the given string to uppercase.

Examples

iex> String.upcase("abcd")
"ABCD"

iex> String.upcase("ab 123 xpto")
"AB 123 XPTO"

iex> String.upcase("olá")
"OLÁ"

valid?(arg1)

Specs

  • valid?(t) :: boolean

Checks whether str contains only valid characters.

Examples

iex> String.valid?("a")
true

iex> String.valid?("ø")
true

iex> String.valid?(<<0xffff :: 16>>)
false

iex> String.valid?("asd" <> <<0xffff :: 16>>)
false

valid_character?(codepoint)

Specs

  • valid_character?(t) :: boolean

Checks whether str is a valid character.

All characters are codepoints, but some codepoints are not valid characters. They may be reserved, private, or other.

More info at: http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Noncharacters

Examples

iex> String.valid_character?("a")
true

iex> String.valid_character?("ø")
true

iex> String.valid_character?("\x{ffff}")
false