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.
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
:
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.