String Functions in Elm

In Elm, string manipulation is handled differently compared to imperative languages. Elm provides a String module with various functions for working with strings. Here’s an example showcasing some of these functions:

import Html exposing (Html, div, text)
import String

main : Html msg
main =
    div []
        [ text ("Contains:  " ++ (String.contains "es" "test" |> Debug.toString))
        , text ("\nCount:     " ++ (String.indexes "t" "test" |> List.length |> String.fromInt))
        , text ("\nHasPrefix: " ++ (String.startsWith "te" "test" |> Debug.toString))
        , text ("\nHasSuffix: " ++ (String.endsWith "st" "test" |> Debug.toString))
        , text ("\nIndex:     " ++ (String.indexes "e" "test" |> List.head |> Maybe.withDefault -1 |> String.fromInt))
        , text ("\nJoin:      " ++ String.join "-" ["a", "b"])
        , text ("\nRepeat:    " ++ String.repeat 5 "a")
        , text ("\nReplace:   " ++ String.replace "o" "0" "foo")
        , text ("\nReplace:   " ++ String.replace "o" "0" "foo" |> String.slice 0 2 |> (\s -> s ++ "o"))
        , text ("\nSplit:     " ++ (String.split "-" "a-b-c-d-e" |> Debug.toString))
        , text ("\nToLower:   " ++ String.toLower "TEST")
        , text ("\nToUpper:   " ++ String.toUpper "test")
        ]

This example demonstrates various string functions available in Elm’s String module. Here’s a breakdown of what each function does:

  • String.contains: Checks if a string contains a substring.
  • String.indexes: Returns a list of all positions where a substring occurs in a string. We use List.length to count occurrences.
  • String.startsWith: Checks if a string starts with a given prefix.
  • String.endsWith: Checks if a string ends with a given suffix.
  • String.indexes: Used here to find the first occurrence of a character.
  • String.join: Joins a list of strings with a separator.
  • String.repeat: Repeats a string a given number of times.
  • String.replace: Replaces all occurrences of a substring.
  • String.split: Splits a string into a list of substrings.
  • String.toLower: Converts a string to lowercase.
  • String.toUpper: Converts a string to uppercase.

Note that Elm’s functional nature means these functions return new strings rather than modifying existing ones. Also, Elm doesn’t have a direct equivalent to Go’s -1 for replacing all occurrences, so String.replace always replaces all occurrences.

To run this program, you would typically compile it with the Elm compiler and then open the resulting HTML file in a browser. The output would be displayed as text in the browser window.