🎓 A1Learner
🔍
0 of 52 lessons completed

Julia Strings

A String is a piece of text written inside double quotes. Julia builds and joins strings with a few simple tools.

Joining strings with *

The * symbol joins strings end to end. The pieces appear in the order they are written.

println("Hello, " * "Ana")
println("ab" * "cd" * "ef")

Building a string from pieces

The string function turns each piece into text and joins the pieces. Numbers become their usual written form.

println(string("Age: ", 31))
println(string("a", 1, "b", 2))

Values inside a string

A dollar sign followed by a variable name drops that variable's value into the text. Brackets after the dollar sign hold a whole expression.

name = "Ana"
println("Hello, $name")
println("Sum: $(3 + 4)")

Counting characters with length

The length function counts every character in a string, including spaces. An empty string has length 0.

println(length("Julia"))
println(length("a b"))
println(length(""))

Example

city = "Oslo"
temp = 4
message = "Weather in " * city
println(message)
println("$city is $temp degrees today")
println(string("Chars in city name: ", length(city)))

Key points

  • Double quotes: text in double quotes is a String.
  • Joining: * joins two strings into one longer string.
  • string function: string() builds one string from pieces of any type.
  • Interpolation: $name inside a string is replaced by the value of the variable name.
  • Expression interpolation: $(...) inside a string is replaced by the value of the expression inside the brackets.
  • Length: length counts the characters in a string.

In this example, city holds the text Oslo and temp holds 4. The first printed line joins two strings with *, the second drops both values into a string with interpolation, and the last builds a label with the string function and the length of the city name.

Note

text is joined with * in Julia, where many other languages use + for this job.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does println("ha" * "ha") print?