String Functions in Julia

using Printf

# We alias printf to a shorter name as we'll use it a lot below.
p = @printf

function main()
    # Here's a sample of the functions available for string manipulation in Julia.
    # Julia has many built-in string functions, and we can also use methods
    # directly on string objects. You can find more functions in the Julia
    # documentation for strings.

    p("Contains:  %s\n", occursin("es", "test"))
    p("Count:     %d\n", count("t", "test"))
    p("StartsWith: %s\n", startswith("test", "te"))
    p("EndsWith: %s\n", endswith("test", "st"))
    p("FindFirst:  %d\n", findfirst(isequal('e'), "test"))
    p("Join:      %s\n", join(["a", "b"], "-"))
    p("Repeat:    %s\n", repeat("a", 5))
    p("Replace:   %s\n", replace("foo", "o" => "0"))
    p("Replace:   %s\n", replace("foo", "o" => "0", count=1))
    p("Split:     %s\n", split("a-b-c-d-e", "-"))
    p("Lowercase: %s\n", lowercase("TEST"))
    p("Uppercase: %s\n", uppercase("test"))
end

main()

This Julia code demonstrates various string functions and methods that are similar to the ones shown in the Go example. Here’s a brief explanation of the differences and similarities:

  1. In Julia, we use the Printf module for formatted printing.
  2. Many string functions in Julia are methods that can be called directly on string objects, unlike in Go where they are package functions.
  3. Julia’s occursin is equivalent to Go’s strings.Contains.
  4. count in Julia works similarly to Go’s strings.Count.
  5. Julia uses startswith and endswith instead of HasPrefix and HasSuffix.
  6. findfirst with isequal is used to find the index of a character, similar to Go’s Index.
  7. join, repeat, replace, split, lowercase, and uppercase work similarly in both languages.
  8. Julia’s replace function uses the => operator to specify replacement pairs.

To run this program, save it as string_functions.jl and use the Julia REPL or run it from the command line:

$ julia string_functions.jl
Contains:  true
Count:     2
StartsWith: true
EndsWith: true
FindFirst:  2
Join:      a-b
Repeat:    aaaaa
Replace:   f00
Replace:   f0o
Split:     SubString{String}["a", "b", "c", "d", "e"]
Lowercase: test
Uppercase: TEST

This example showcases Julia’s string manipulation capabilities, which are quite similar to those available in other languages, but with syntax and conventions specific to Julia.