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
The GNU Linux core utilities contain lots of goodies.
To reverse strings, use rev.
$ echo "Hello, World!" | rev
!dlroW ,olleH
rev also works with files to reverse each line.
$ printf '%s\n' one two three > myfile
$ rev myfile
eno
owt
eerht
There are other ways to do this, but none are a simple as rev.
grep -o . <<< "$string" | tac | paste -s -d ''
perl -lne 'print scalar reverse' <<< "$string"
# etc
Looping
Looping
In a bash loop, we are looping over the indices of the characters.
Bash strings and arrays use zero-based indexing.
reversed=''
for ((i = 0; i < ${#string}; i++)); do
reversed="${string:i:1}$reversed"
done
- We loop from zero up to (but not including) the string length (
${#string}).
- Extracting the character at index
i is done with the ${var:offset:length} parameter expansion.
- We prepend the character to the accumulating variable to reverse the string.
Finding the string length is a surprisingly expensive operation in bash (more details in the Performance article).
We don’t have to re-calculate it for every loop iteration, just do it once.
reversed=''
len=${#string}
for ((i = 0; i < len; i++)); do
reversed="${string:i:1}$reversed"
done
An alternate way to calculate it just once is to loop backwards.
reversed=''
for ((i = ${#string} - 1; i >= 0; i--)); do
reversed+="${string:i:1}"
done
- Here, we start the loop at one less than the string length, which is the index of the last character, and we loop down to (and including) zero.
- Since we’re accessing the characters in the reverse order, we’ll append to the accumulating variable.
Another performance note: accessing each character with this parameter expansion is still slow: bash has to walk the string until reaching the desired index.
The most efficient solution is discussed in the Performance article).
Source: Exercism bash/reverse-string