Reverse characters in a string

From CodeCodex

Related content:

Implementations[edit]

C[edit]

There are couple different ways of reversing a string in C. One way is to use an extra char to store the values being switched.

#include <stdio.h>
#include <string.h>
 
void reverse(char* s)
{
    int i;
    char temp;
    size_t l = strlen(s);
    
    for (i = 0; i < (l/2); ++i) {
       temp = s[i];
       s[i] = s[l - i];
       s[l - i] = temp;
    }
}

The other way is to use the XOR operator, which won't require any extra storage while reversing the string.

#include <stdio.h>
#include <string.h>
 
void reverse(char* s)
{
    int i;
    size_t l = strlen(s);
    
    for (i = 0; i < (l/2); ++i) {
       s[i] ^= s[l - i];
       s[l - i] ^= s[i];
       s[i] ^= s[l - i];
    }
}
  • Note: These will only work on null terminated strings (end in '\0').

C++[edit]

std::string foo = "born2c0de";
std::reverse(foo.begin(), foo.end());
std::cout << foo << std::endl;

Erlang[edit]

Rstring = lists:reverse("abcdef").

Haskell[edit]

a_string = reverse a_string

Java[edit]

 new StringBuilder(a_string).reverse().toString()

OCaml[edit]

# let rec rev s =
    let n = String.length s in
    for i=0 to (n - 1) / 2 do
      let c = s.[i] in
      s.[i] <- s.[n-i-1];
      s.[n-i-1] <- c;
    done;
    s;;
val rev : string -> string = <fun>

For example:

# rev "born2c0dex";;
- : string = "xed0c2nrob"

Perl[edit]

 $a_string = reverse $a_string;

PHP[edit]

 $a_string = strrev($a_string);

Python[edit]

New in python 2.4:

a_string = reversed(a_string)

New in python 2.3:

a_string = a_string[::-1]

Alternatively:

a_string = list(a_string)
a_string.reverse()
"".join(a_string)

Another alternative:

"".join([a_string[i] for i in xrange(len(a_string)-1, -1, -1)])

Rexx[edit]

Object Rexx[edit]

Object Rexx is freely available from http://www.oorexx.org/

"!iH"~reverse   /* Reverses the characters "!iH" to form "Hi!"  */

Classic Rexx[edit]

REVERSE('ABc.') /* Reverses the characters 'ABc.' to form'.cBA'  */

Ruby[edit]

# return the reverse of a string
str = "abcdefg"
reverse_str = str.reverse

# at this point reverse_str is "gfedcba" and str is "abcdefg"

# reverse a string in place
str.reverse!

# now both str and reverse_str are "gfedcba"

Scheme[edit]

(list->string (reverse (string->list "ABc")))  
/* Turns "ABc" into a list ("A", "B", "c"), then reverses the list and converts it to a string back again */

You can also define a global method reverse-string like this:

(define (reverse-string x)
    (list->string (reverse (string->list x))))

Tcl[edit]

string reverse "abcdefg"