▒ OCaml 소스:  testStringReverse.ml

open Printf;;

let reverse s =
    let s2 = "" ^ s in
    let n = String.length s in
    for i = 0 to (n/2 - 1) do
        let t = s2.[i] in
        s2.[i] <- s2.[n - 1 - i];
        s2.[n - 1 - i] <- t
    done ;
    s2;;

let reverse2 s =
    let s2 = "" ^ s in
    let n = String.length s in
    let isTwo = ref false in
    for i = 0 to (n - 1) do
        if !isTwo = false then begin
            let t = s.[i] in
            (* printf "  %d\n" (int_of_char t) ; *)
            if (int_of_char t) > 127 then begin
                isTwo := true;
                s2.[n - 1 - i - 1] <- t ;
                s2.[n - 1 - i] <- s.[i + 1]
            end
            else begin
                isTwo := false;
                s2.[n - 1 - i] <- t
            end
        end
        else
            isTwo := false;
    done ;
    s2;;

let a = "Hello, world!" in
let b = "안녕하세요?" in
let a2 = reverse a in
let a3 = reverse a in
let b2 = reverse b in
let b3 = reverse2 b in

printf " reverse: %s\n" a2;
printf "original: %s\n" a;
printf "reverse2: %s\n" a3;
printf "original: %s\n" a;
print_newline();
printf " reverse: %s\n" b2;
printf "original: %s\n" b;
printf "reverse2: %s\n" b3;
printf "original: %s\n" b;

(*
let mutable arr = a.ToCharArray()
arr <- Array.rev arr
System.Console.WriteLine(new System.String(arr))
arr <- b.ToCharArray()
arr <- Array.rev arr
System.Console.WriteLine(new System.String(arr))
*)

(*
Expected result:
 reverse: !dlrow ,olleH
original: Hello, world!
reverse2: !dlrow ,olleH
original: Hello, world!

 reverse: ?岳세逑楹횡
original: 안녕하세요?
reverse2: ?요세하녕안
original: 안녕하세요?
*)

 

주: 소스 파일은 ms949 인코딩으로 저장되어야 한다.

 

Posted by Scripter
,