Reversing a string

From Rosetta Code

Jump to: navigation, search

Programming Task
This is a programming task. It lays out a problem which Rosetta Code users are encouraged to solve, using languages they know.

Code examples should be formatted along the lines of one of the existing prototypes.

Take a string and reverse it. For example, "asdf" becomes "fdsa".

Contents

[edit] Ada

 
with Ada.Text_IO; use Ada.Text_IO;
 
procedure Reverse_String is
   function Reverse_It (Item : String) return String is
      Result : String (Item'Range);
   begin
      for I in Item'range loop
         Result (Result'Last - I + Item'First) := Item (I);
      end loop;
      return Result;
   end Reverse_It;
begin
   Put_Line (Reverse_It (Get_Line));
end Reverse_String;
 

[edit] APL

      ⌽'asdf'
fdsa

[edit] BASIC

Works with: QuickBasic version 4.5

FUNCTION reverse$(a$)
   b$ = ""
   FOR i = 1 TO LEN(a$)
      b$ = MID$(a$, i, 1) + b$
   NEXT i
   reverse$ = b$
END FUNCTION

[edit] C

 
#include <string.h>
#include <stdio.h>
 
/* This function assumes the passed pointer points to a valid, zero-terminated string */
void reverse(char* s)
{
  char* last;
  if (*s == '\0') /* special case: empty string */
    return;       /* nothing to do in that case */
 
  last = s + strlen(s) - 1; /* points to last actual character */
                            /* valid because here we know there's at least one character in the string */
 
  while (last > s)
  {
    char ch = *s;
    *s = *last;
    *last = ch;
    ++s;
    --last;
  }
}
 
int main()
{
  char text[] = "asdf";
  reverse(text);
  printf("%s\n", text);
}
 

[edit] C++

 
#include <iostream>
#include <string>
#include <algorithm>
 
int main()
{
  std::string s;
  std::get_line(std::cin, s);
  std::reverse(s.begin(), s.end()); // modifies s
  std::cout << s << std::endl;
  return 0;
}
 

[edit] ColdFusion

You can reverse anything that can be written to the document in hashmarks (i.e. strings, numbers, now( ), etc.).

<cfset myString  = "asdf" />
<cfset myString  = reverse( myString ) />

[edit] D

D has a built-in reverse function for array types (including string=char[]). It is an in-place function.

string s ;
s.reverse ;
s.dup.reverse ; // preserve original array

[edit] Forth

: cexch { a1 a2 -- }
  a1 c@ a2 c@  a1 c! a2 c! ;
: reverse ( caddr len -- )
  1- bounds
  begin  2dup >
  while  2dup cexch
         1+ swap 1- swap
  repeat
  2drop ;
s" testing" 2dup reverse type   \ gnitset

[edit] Fortran

Works with: Fortran version 90 and later

PROGRAM Example

  CHARACTER(80) :: str = "This is a string"
  CHARACTER :: temp
  INTEGER :: i, length

  WRITE (*,*) str
  length = LEN_TRIM(str) ! Ignores trailing blanks. Use LEN(str) to reverse those as well
  DO i = 1, length/2
     temp = str(i:i)
     str(i:i) = str(length+1-i:length+1-i)
     str(length+1-i:length+1-i) = temp
  END DO
  WRITE(*,*) str

END PROGRAM Example

Output:

This is a string
gnirts a si sihT

[edit] Haskell

string = "asdf"
reversed = reverse string

[edit] J

Reverse (|.) reverses items of any shape or type.

   |.'asdf'
fdsa

[edit] Java

 
public static String reverseString(String s) {
    return new StringBuffer(s).reverse().toString();
}
 

[edit] JavaScript

var a = "cat".split("");
a.reverse();
print(a.join(""));   // tac

[edit] Logo

REVERSE works on both words and lists.

print reverse "cat   ; tac

[edit] Mathematica

StringReverse["asdf"]

[edit] Nial

reverse 'asdf'
=fdsa

[edit] OCaml

let rev_string _str =
  let str = String.copy _str
  and last = String.length _str - 1 in
  for i = 0 to last / 2 do
    let j = last - i in
    str.[i] <- _str.[j];
    str.[j] <- _str.[i];
  done;
  (str)
 

[edit] Perl

reverse $string

[edit] PHP

strrev($string)

[edit] Pop11

define reverse_string(s);
    lvars i, l = length(s);
    for i from l by -1 to 1 do
        s(i);
    endfor;
    consstring(l);
enddefine;

[edit] Python

[edit] Optimized for user input

raw_input()[::-1]

[edit] Already known string

string[::-1]

[edit] Ruby

str = "asdf"
reversed = str.reverse
Personal tools