String Functions in Erlang

The standard library’s string module provides many useful string-related functions. Here are some examples to give you a sense of the module.

-module(string_functions).
-export([main/0]).

main() ->
    P = fun(Str) -> io:format("~s~n", [Str]) end,

    P(io_lib:format("Contains:  ~p", [string:str("test", "es") > 0])),
    P(io_lib:format("Count:     ~p", [length(string:find_all("test", "t"))])),
    P(io_lib:format("HasPrefix: ~p", [string:prefix("test", "te") /= nomatch])),
    P(io_lib:format("HasSuffix: ~p", [string:suffix("test", "st") /= nomatch])),
    P(io_lib:format("Index:     ~p", [string:str("test", "e") - 1])),
    P(io_lib:format("Join:      ~p", [string:join(["a", "b"], "-")])),
    P(io_lib:format("Repeat:    ~p", [string:copies("a", 5)])),
    P(io_lib:format("Replace:   ~p", [string:replace("foo", "o", "0", all)])),
    P(io_lib:format("Replace:   ~p", [string:replace("foo", "o", "0", [{scope, {1,1}}])])),
    P(io_lib:format("Split:     ~p", [string:split("a-b-c-d-e", "-", all)])),
    P(io_lib:format("ToLower:   ~p", [string:lowercase("TEST")])),
    P(io_lib:format("ToUpper:   ~p", [string:uppercase("test")])).

Here’s a sample of the functions available in string. Since these are functions from the module, not methods on the string object itself, we need to pass the string in question as an argument to the function. You can find more functions in the string module documentation.

To run the program, save it as string_functions.erl and use erlc to compile it, then run it with erl:

$ erlc string_functions.erl
$ erl -noshell -s string_functions main -s init stop
Contains:  true
Count:     2
HasPrefix: true
HasSuffix: true
Index:     1
Join:      "a-b"
Repeat:    "aaaaa"
Replace:   "f00"
Replace:   "f0o"
Split:     ["a","b","c","d","e"]
ToLower:   "test"
ToUpper:   "TEST"

Note that Erlang’s string functions work a bit differently from those in some other languages. For example, string:str/2 returns the position of the substring (1-indexed) or 0 if not found, so we subtract 1 to make it 0-indexed like in many other languages. Also, Erlang doesn’t have a direct equivalent to Go’s strings.Count, so we use string:find_all/2 and count the results.

The string:replace/4 function in Erlang allows specifying whether to replace all occurrences or just the first one using the all or {scope, {1,1}} options, respectively.

Erlang’s string module provides powerful string manipulation capabilities, although the syntax and exact function names might differ from what you’re used to in other languages.