String Functions in Crystal
The standard library’s String
class provides many useful string-related methods. Here are some examples to give you a sense of the available functionality.
When you run this program, you’ll see:
In Crystal, many of these operations are methods on the String
class rather than functions in a separate module. This allows for a more object-oriented approach to string manipulation. The syntax is generally similar to Ruby, which Crystal’s design is heavily inspired by.
Note that some method names are slightly different in Crystal compared to other languages:
includes?
is used instead ofContains
starts_with?
andends_with?
are used instead ofHasPrefix
andHasSuffix
gsub
is used for global substitution (replacing all occurrences)sub
is used for replacing the first occurrence only
Crystal’s standard library provides a rich set of string manipulation methods, making it easy to perform common operations on strings.