🎓 A1Learner
🔍
0 of 52 lessons completed

Julia String Functions

String functions read and reshape the text inside a string. They give back pieces, checks, and changed copies of the original text.

Picking characters and slices

Positions in a string start at 1, not 0. A single position gives a Char, and a range gives a String.

word = "Haskell"
println("Haskell"[1])
println("Haskell"[end])
println("Haskell"[1:4])
println(first(word))
println(last(word))

Searching and replacing

The occursin function checks whether a small piece appears inside a string. The replace function swaps one piece for another.

println(occursin("ell", "hello"))
println(occursin("z", "hello"))
println(replace("hello", "l" => "L"))

Case, trimming, and repeating

The uppercase and lowercase functions change every letter in a string. The strip function removes spaces at both ends, and repeat copies a string a set number of times.

println(uppercase("hello"))
println(lowercase("HeLLo"))
println(strip("  hi  "))
println(repeat("ab", 3))

Splitting a string into pieces

The split function breaks a string into pieces at its spaces. Joining the pieces back with join, or counting them with length, shows the result plainly.

println(join(split("a b c"), "-"))
println(length(split("one two three four")))

Example

title = "  julia rocks  "
clean = strip(title)
println(uppercase(clean))
println(clean[1:5])
println(occursin("rocks", clean))
println(replace(clean, "rocks" => "shines"))
println(length(split(clean)))

Key points

  • Indexing: a number in square brackets picks one character, and counting starts at 1.
  • Last character: end inside the brackets names the last position, and first and last give the end characters directly.
  • Slicing: a range such as 1:4 inside the brackets gives the characters from position 1 to position 4 as a new string.
  • Search: occursin(needle, text) is true when the needle text appears inside the bigger text.
  • Replace: replace(text, old => new) gives a copy with every old piece swapped for the new piece.
  • Case and trimming: uppercase and lowercase change the case of every letter, and strip removes spaces at both ends.

In this example, strip first removes the spaces around the title and the result is stored in clean. The lines then print the text in uppercase, its first five characters as a slice, a search check for the word rocks, a copy with rocks replaced by shines, and the count of words from split.

Note

split gives back separate pieces, and printing join or length of those pieces shows a plain result.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does println("Julia"[2]) print?