Introduction
Reversing strings (reading them from right to left, rather than from left to right) is a surprisingly common task in programming.
For example, in bioinformatics, reversing the sequence of DNA or RNA strings is often important for various analyses, such as finding complementary strands or identifying palindromic sequences that have biological significance.
Instructions
Instructions
Your task is to reverse a given string.
Some examples:
- Turn
"stressed" into "desserts".
- Turn
"strops" into "sports".
- Turn
"racecar" into "racecar".
Dig Deeper
Use an array
Using an array
module ReverseString
def self.reverse(input : String) : String
result = Array(Char).new(input.size)
input.each_char do |char|
result.unshift(char)
end
result.join
end
end
The method takes a String as an argument and returns a String.
An empty array stores the reversed string which stores Char.
The reason for using Char instead of String is because Char is lighter than String, and we only store one character at a time.
The Array is given the size of the string to be reversed, this makes the array doesn’t have to be resized later which is more efficient.
The each_char method iterates over each character in the string.
For each character so are they unshifted into the array.
The unshift method adds the character to the beginning of the array.
This means the first character in the string will be the last character in the array.
The join method converts the array back to a string.
Uses String::Builder
Using String::Builder
module ReverseString
def self.reverse(input : String) : String
String.build(input.size) do |builder|
(0...input.size).reverse_each do |i|
builder << input[i]
end
end
end
end
The method takes a String as an argument and returns a String.
The constructor, String.build, takes the size of the string as an argument.
The String.build method is from the String::Builder class.
The String::Builder allows writing to a buffer in memory.
The constructor is given the size of the string to be reversed.
This is due to the fact that we already know the size of the string.
This is more efficient than using the default size of 16 and then resizing the string later.
A Range is created from 0 to the size of the string (exclusive).
The reverse_each method iterates over the range in reverse order.
So the last index of the string is the first value given to the block.
For each index, the character at that index is appended to the string builder.
The String.build method is what is implicitly returned from the method.
Uses Reverse
Reverse
module ReverseString
def self.reverse(input : String) : String
input.reverse
end
end
This is the simplest and most exemplary solution, using the built-in String#reverse method.
Internally, it uses a very optimized implementation, using a buffer and working directly on the string’s bytes.
If curious, check the source code.
Source: Exercism crystal/reverse-string