Data Structures
Crystal Strings
Working with Strings
Crystal strings are immutable UTF-8, with String methods.
Introduction to Crystal Strings
In Crystal, strings are a fundamental data structure that represents sequences of characters. Crystal strings are immutable, meaning once a string is created, it cannot be changed. This immutability is crucial for performance and safety. Crystal strings are encoded in UTF-8, allowing them to represent text from any language.
Creating Strings
Creating strings in Crystal is straightforward. You can define a string by enclosing text in double quotes.
String Interpolation
Crystal supports string interpolation, allowing you to embed expressions inside strings. To interpolate, use #{}
within a string.
Common String Methods
Crystal provides a variety of methods to manipulate strings. Here are some commonly used ones:
length
: Returns the number of characters in the string.upcase
: Converts all characters to uppercase.downcase
: Converts all characters to lowercase.split
: Splits a string into an array based on a delimiter.
String Immutability
As mentioned earlier, Crystal strings are immutable. This means that any operation on a string that seems to modify it will actually return a new string. For example, using upcase
on a string does not change the original string but returns a new one.
Conclusion
Crystal strings offer a robust and efficient way to handle text in your programs. Their immutability and support for UTF-8 encoding make them a powerful tool for developers working with internationalized applications. Understanding and utilizing the available string methods can significantly streamline your text processing tasks in Crystal.