Julia Characters
A Char is a single character written inside single quotes. Every character also has a number code that Julia can reveal and use.
A Char is one character
Single quotes make a Char. Printing a Char shows the character alone, with no quotes.
letter = 'J'
println(letter)
println(letter == 'J')
println('x')Character codes both ways
The Int function reveals the number code of a character. The Char function turns a code back into its character.
println(Int('A'))
println(Int('a'))
println(Char(97))
println(Char(66))Moving and checking characters
Adding a whole number to a Char steps to a later character. The isletter and isdigit functions check what kind of character they are given.
println('a' + 1)
println('a' + 2)
println(isletter('a'))
println(isdigit('7'))
println(isdigit('a'))Example
start = 'm'
println(start)
println(Int(start))
println(start + 1)
println(Char(Int(start) + 2))
println(isletter(start))
println(isdigit(start))Key points
- Single quotes: text in single quotes is one Char, never a String.
- One only: a Char holds exactly one character, such as a letter, a digit, or a space.
- Code number: Int(c) gives the number code of a character.
- From a code: Char(n) gives the character that has the number code n.
- Character arithmetic: adding a whole number to a Char moves that many steps through the character codes.
- Checks: isletter(c) is true for a letter and isdigit(c) is true for a digit character.
In this example, start holds the character m. The lines print the character itself, its code 109, the next character n from adding 1, the character o built from the code plus 2, and two checks showing m is a letter but not a digit.
Note
a digit character such as '7' is text of length one, not the number 7.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What does println(Char(65)) print?