Strings and Runes in Julia
Our first example demonstrates strings and runes in Julia. Julia strings are sequences of Unicode characters, similar to UTF-8 encoded text in other languages.
In Julia, strings are UTF-8 encoded by default. Here’s a breakdown of the code:
We define a constant string
s
containing Thai characters.sizeof(s)
gives the length of the string in bytes, similar tolen(s)
in Go.We use
codeunits(s)
to iterate over the raw bytes of the string and print their hexadecimal representation.length(s)
counts the number of characters in the string, equivalent toutf8.RuneCountInString(s)
in Go.We use
enumerate(s)
to iterate over each character and its index in the string.nextind(s, 0, i)
gives us the byte index of each character.We demonstrate another way to iterate over the string using the
iterate
function, which is similar toutf8.DecodeRuneInString
in Go.We define an
examine_char
function that checks for specific characters, similar to theexamineRune
function in Go.Finally, we iterate over the string again, calling
examine_char
for each character.
In Julia, there’s no need to explicitly import packages for basic string operations. The language provides built-in support for Unicode strings and characters.
To run this program, save it as strings_and_chars.jl
and use the Julia REPL or run it from the command line:
This will output the character information, byte representation, and the results of character examination.