String Functions
Prerequisites: Strings
The most useful built-in string functions:
s = " Julia is fast "
t = strip(s)
println("[", t, "]")
println(uppercase(t), " | ", lowercase(t))
println(occursin("fast", t), " ", startswith(t, "Jul"), " ", endswith(t, "!"))
println(replace(t, "fast" => "fun"))
println(split("a,b,,c", ","))
println(join(["x", "y", "z"], " + "))
println(findfirst("is", t))
println(reverse("stressed"))
[Julia is fast]
JULIA IS FAST | julia is fast
true true false
Julia is fun
SubString{String}["a", "b", "", "c"]
x + y + z
7:8
desserts
strip,lstrip,rstripremove whitespace.occursin(needle, haystack)checks for a substring.replace(s, old => new)uses a pair (=>) for the replacement.splitreturns a vector of substrings;joindoes the reverse.findfirstreturns the range of indices where the match starts and ends (ornothing).
Formatting numbers
The Printf standard library gives C-style formatting:
using Printf
price = 1234.5
@printf("Price: %.2f\n", price)
@printf("%-8s|%6d|\n", "apples", 42)
label = @sprintf("%05.1f%%", 7.26)
println(label)
println(lpad(7, 3, "0"), " ", rpad("ab", 5, "."), "|")
Price: 1234.50
apples | 42|
007.3%
007 ab...|
@printfprints;@sprintfreturns a string.%.2ftwo decimals,%6dinteger in 6 columns,%-8sleft-aligned string,%%a literal percent sign.lpadandrpadpad a value to a width.
Regular expressions
Regexes are written r"...":
text = "Order 66 shipped on 2024-05-17, order 67 on 2024-06-02"
println(occursin(r"\d{4}-\d{2}-\d{2}", text))
m = match(r"(\d{4})-(\d{2})-(\d{2})", text)
println(m.match, " year=", m[1])
for m in eachmatch(r"order (\d+)"i, text)
println("order number: ", m[1])
end
println(replace(text, r"\d{4}-\d{2}-\d{2}" => "<date>"))
true
2024-05-17 year=2024
order number: 66
order number: 67
Order 66 shipped on <date>, order 67 on <date>
The i after the closing quote makes the match case-insensitive. Test
your patterns interactively with the regex tester.
Practice
Turn "the quick brown fox" into "The Quick Brown Fox" by splitting
into words, capitalizing each, and joining them.
Show solution
words = split("the quick brown fox")
println(join(uppercasefirst.(words), " "))
The Quick Brown Fox
(uppercasefirst.(words) applies the function to every word — the dot
syntax you'll meet properly in a later lesson. titlecase does the whole
job in one call.)