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.
# We alias puts to a shorter name as we'll use it a lot below.
alias p = puts
# Here's a sample of the methods available for strings.
# These are methods on the String object itself,
# so we call them directly on the string in question.
# You can find more methods in the Crystal documentation.
p "Contains: #{"test".includes?("es")}"
p "Count: #{"test".count('t')}"
p "HasPrefix: #{"test".starts_with?("te")}"
p "HasSuffix: #{"test".ends_with?("st")}"
p "Index: #{"test".index("e")}"
p "Join: #{["a", "b"].join("-")}"
p "Repeat: #{"a" * 5}"
p "Replace: #{"foo".gsub("o", "0")}"
p "Replace: #{"foo".sub("o", "0")}"
p "Split: #{"a-b-c-d-e".split("-")}"
p "ToLower: #{"TEST".downcase}"
p "ToUpper: #{"test".upcase}"
When you run this program, you’ll see:
$ crystal string_functions.cr
Contains: true
Count: 2
HasPrefix: true
HasSuffix: true
Index: 1
Join: a-b
Repeat: aaaaa
Replace: f00
Replace: f0o
Split: ["a", "b", "c", "d", "e"]
ToLower: test
ToUpper: TEST
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.