Difference between revisions of "Reverse characters in a string"

From CodeCodex

Line 30: Line 30:
 
</pre>
 
</pre>
 
Original source: [http://code.dreamincode.net/snippet313.htm]
 
Original source: [http://code.dreamincode.net/snippet313.htm]
 +
===OCaml===
 +
<pre>
 +
# 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>
 +
</pre>
 +
For example:
 +
<pre>
 +
# rev "born2c0dex";;
 +
- : string = "xed0c2nrob"
 +
</pre>
  
 
[[Category:String]]
 
[[Category:String]]
 
[[Category:C plus plus]]
 
[[Category:C plus plus]]

Revision as of 17:39, 15 August 2006

Related content:

Implementations

C++

/*
 * Recursive Reverse String Algorithm
 *
 * Suddenly I get this wild...mad idea to use recursion.
 * And wow...does that look neat :)
 *
 * Written by: Sanchit Karve born2c0de AT hotmail.com
 *
 */
 
#include <iostream>
 
void ret_str(char* s)
{
    if(*s != '\0')
         ret_str(s+1);
 
    cout<<*(s);
}
 
int main()
{
   ret_str("born2c0de");
   return 0;
}

Original source: [1]

OCaml

# 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"