Strings
Prerequisites: Variables
Strings are text in double quotes. A single character in single
quotes is a Char:
name = "Ada"
greeting = "Hello, " * name * "!"
println(greeting)
println("$name has $(length(name)) letters")
println("2 + 3 = $(2 + 3)")
println(repeat("ab", 3), " ", "ab"^3)
println(typeof('A'), " ", 'A' + 1, " ", Int('A'))
Hello, Ada!
Ada has 3 letters
2 + 3 = 5
ababab ababab
Char B 65
*concatenates strings (Julia's reasoning: concatenation isn't commutative, like multiplication of matrices).$nameinterpolates a variable;$(expression)interpolates any expression.^repeats a string.
Indexing
Strings are indexed from 1, and end means the last index:
s = "Julia"
println(s[1], " ", s[end], " ", s[2:4])
println(first(s, 2), " ", last(s, 3))
println(length(s))
for c in s
print(c, "-")
end
println()
J a uli
Ju lia
5
J-u-l-i-a-
s[1] is a Char; s[2:4] (a range of indices) is a String.
Unicode
Julia strings are UTF-8. Indexes are byte positions, so for text with
non-ASCII characters, prefer first, last, iteration, or
collect(s) over raw indexes:
word = "naïve"
println(length(word), " characters, ", sizeof(word), " bytes")
println(collect(word))
println(first(word, 3))
5 characters, 6 bytes
['n', 'a', 'ï', 'v', 'e']
naï
Special strings
println("Tab:\tNew line:\nQuote: \" Dollar: \$5")
poem = """
Roses are red,
Julia is fast.
"""
print(poem)
println(raw"C:\Users\ada")
Tab: New line:
Quote: " Dollar: $5
Roses are red,
Julia is fast.
C:\Users\ada
- Escape sequences:
\n,\t,\",\\, and\$for a literal dollar sign. - Triple-quoted strings span lines and remove the common indentation.
raw"..."strings don't process escapes or interpolation.
Practice
Given first_name = "grace" and last_name = "hopper", print
Hopper, Grace (11 letters). Hint: uppercasefirst.
Show solution
first_name = "grace"
last_name = "hopper"
full = uppercasefirst(last_name) * ", " * uppercasefirst(first_name)
println("$full ($(length(first_name) + length(last_name)) letters)")
Hopper, Grace (11 letters)