Strings and Runes in Racket
Our first program will demonstrate string and character handling in Racket. Here’s the full source code:
Let’s break down the code and explain its components:
We define a string
s
containing the Thai word for “hello”.We print the length of the string using
string-length
. In Racket, this gives us the number of characters, not bytes.To print the hexadecimal representation of each byte, we first convert the string to a byte string using
string->bytes/utf-8
, then iterate over each byte.We print the character count, which in Racket is the same as the string length.
We iterate over each character in the string, printing its Unicode code point, the character itself, and its position in the string.
We define a function
examine-char
that checks if a character is ’t’ or ‘ส’ and prints a message accordingly.Finally, we use the
examine-char
function on each character in our string.
To run this program, save it as strings-and-chars.rkt
and use the Racket interpreter:
This example demonstrates how Racket handles Unicode strings and characters. Unlike some languages, Racket treats strings as sequences of characters rather than bytes, which simplifies many string operations but may require explicit conversion to bytes when needed.