Reverse a String

Another “classic” programming interview question.

The Question

Given a random string as input, write a script which reverses it character-for-character.

The Answer

First off, I feel I should mention that the following is cheating!

$ echo "This is a sentence" | rev
ecnetnes a si sihT

The equivalent BASH script:

#!/bin/bash
#set -xv
echo "$1" | rev

And it’s output:

$ ./reverse_string "Kinda long test sentence using rev"
ver gnisu ecnetnes tset gnol adniK

Now on to theĀ real solution!

Both of the scripts below are identical, except that the first script uses a for loop and the second uses a while loop.

For loop:

#!/bin/bash
#set -xv

string="$1"
reverse_string=""
string_length="${#string}"

for (( i="$string_length"; i>=0; i-- )) 
do
     reverse_string="$reverse_string${string:$i:1}"
done

echo "$reverse_string"

While loop:

#!/bin/bash
#set -xv

string="$1"
reverse_string=""
string_length="${#string}"

while (( "$string_length">=1 )) 
do
     string_length=$(( $string_length - 1 ))
     reverse_string="$reverse_string${string:$string_length:1}"
done

echo "$reverse_string"

In either case, after you make the file executable

chmod +x reverse_string

and run it given a parameter, it will be reversed

$ ./reverse_string 123456789
987654321
$ ./reverse_string abcdefghijklmnopqrstuvwxyz
zyxwvutsrqponmlkjihgfedcba
$ ./reverse_string "this is a long, horrible string to reverse"
esrever ot gnirts elbirroh ,gnol a si siht
Tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.

Protected by WP Anti Spam