Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse the order of characters in a string

Tags:

bash

People also ask

What returns the characters in the string in reverse order?

With a string as an argument, reversed() returns an iterator that yields characters from the input string in reverse order.

How do you reverse the order of words in a string in C?

Within this C Program to reverse words in a string Here, we used For Loop to iterate each and every character in a String, and remove all the duplicate characters in it. Do the same for j = 7, j = 8, j= 9, and j = 10. Next, it will start the First For Loop iteration where i = 4.


I know you said "without third-party tools", but sometimes a tool is just too obviously the right one, plus it's installed on most Linux systems by default:

[madhatta@risby tmp]$ echo 12345 | rev
54321

See rev's man page for more.


Simple:

var="12345"
copy=${var}

len=${#copy}
for((i=$len-1;i>=0;i--)); do rev="$rev${copy:$i:1}"; done

echo "var: $var, rev: $rev"

Output:

$ bash rev
var: 12345, rev: 54321

Presume that a variable 'var' has the value '123'

var="123"

Reverse the string and store in a new variable 'rav':

rav=$(echo $var | rev)

You'll see the 'rav' has the value of '321' using echo.

echo $rav

rev | tail -r (BSD) or rev | tac (GNU) also reverse lines:

$ rev <<< $'12\n34' | tail -r
43
21
$ rev <<< $'12\n34' | gtac
43
21

If LC_CTYPE is C, rev reverses the bytes of multibyte characters:

$ LC_CTYPE=C rev <<< あの
��め�
$ export LC_ALL=C; LC_ALL=en_US.UTF-8 rev <<< あの
のあ

A bash solution improving over @osdyng answer (my edit was not accepted):

var="12345"     rev=""

for(( i=0 ; i<${#var} ; i++ )); do rev="${var:i:1}$rev"; done

echo "var: $var, rev: $rev"

Or an even simpler (bash) loop:

var=$1   len="${#var}"   i=0   rev=""

while (( i<len )); do rev="${var:i++:1}$rev"; done

echo "var: $var, rev: $rev"

A POSIX solution:

var="12345"     rev=""    i=1

while  [ "$i" -le "${#var}" ]
do     rev="$(echo "$var" | awk -v i="$i" '{print(substr($0,i,1))}')$rev"
       : $(( i+=1 ))
done

echo "var: $var, rev: $rev"

Note: This works on multi byte strings. Cut solutions will work only in ASCII (1 byte) strings.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!