fn main() {
    let strings = vec![
        String::from("1001110011"),
        String::from("1110111011"),
        String::from("0010010010"),
        String::from("1010101010"),
        String::from("1111111111"),
        String::from("0100101101"),
        String::from("0100100"),
        String::from("101"),
        String::from("11"),
        String::from("00"),
        String::from("1"),
    ];
    for string in strings {
        match rep_string(&string) {
            Some(rep_string) => println!(
                "Longuest rep-string for '{}' is '{}' ({} chars)",
                string,
                rep_string,
                rep_string.len(),
            ),
            None => println!("No rep-string found for '{}'", string),
        };
    }
}

fn rep_string(string: &str) -> Option<&str> {
    let index = string.len() / 2;

    for split_index in (1..=index).rev() {
        let mut is_rep_string = true;
        let (first, last) = string.split_at(split_index);

        let inter = last.chars().collect::<Vec<char>>();
        let mut iter = inter.chunks_exact(split_index);
        for chunk in iter.by_ref() {
            if first != chunk.iter().collect::<String>() {
                is_rep_string = false;
                break;
            }
        }
        let rmnd = iter.remainder().iter().collect::<String>();

        // Check that the remainder starts with the rep-string
        if !first.starts_with(rmnd.as_str()) {
            is_rep_string = false;
        }

        if is_rep_string {
            return Some(first);
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::rep_string;
    use std::collections::HashMap;

    #[test]
    fn test_rep_string() {
        let mut results = HashMap::new();
        results.insert(String::from("1001110011"), Some("10011"));
        results.insert(String::from("1110111011"), Some("1110"));
        results.insert(String::from("0010010010"), Some("001"));
        results.insert(String::from("1010101010"), Some("1010"));
        results.insert(String::from("1111111111"), Some("11111"));
        results.insert(String::from("0100101101"), None);
        results.insert(String::from("0100100"), Some("010"));
        results.insert(String::from("101"), None);
        results.insert(String::from("11"), Some("1"));
        results.insert(String::from("00"), Some("0"));
        results.insert(String::from("1"), None);

        for (input, expected) in results {
            assert_eq!(expected, rep_string(&input));
        }
    }
}


object RepString extends App {
  def repsOf(s: String) = s.trim match {
    case s if s.length < 2 => Nil
    case s => (1 to (s.length/2)).map(s take _)
        .filter(_ * s.length take s.length equals s)
  }

  val tests = Array(
    "1001110011",
    "1110111011",
    "0010010010",
    "1010101010",
    "1111111111",
    "0100101101",
    "0100100",
    "101",
    "11",
    "00",
    "1"
  )
  def printReps(s: String) = repsOf(s) match {
    case Nil => s+": NO"
    case r => s+": YES ("+r.mkString(", ")+")"
  }
  val todo = if (args.length > 0) args else tests
  todo.map(printReps).foreach(println)
}


@echo off
setlocal enabledelayedexpansion
call :reverse %1 res
echo %res%
goto :eof

:reverse
set str=%~1
set cnt=0
:loop
if "%str%" equ "" (
	goto :eof
	)
set chr=!str:~0,1!
set str=%str:~1%
set %2=%chr%!%2!
goto loop


      PRINT FNreverse("The five boxing wizards jump quickly")
      END

      DEF FNreverse(A$)
      LOCAL B$, C%
      FOR C% = LEN(A$) TO 1 STEP -1
        B$ += MID$(A$,C%,1)
      NEXT
      = B$


Module checkit {
      Document A$={Alfa, beta}
      Save.Doc A$, "this.aaa"
      Print Exist("this.aaa")=true
      dos "cd "+quote$(dir$)+" && del this.bbb", 100;  ' using; to close dos window, and 100ms for waiting
      Name this.aaa as this.bbb
      Rem : Name "this.aaa" as "this.bbb"  ' we can use strings or variables
      Print Exist("this.bbb")=true
}
checkit


use FileTools in
  Rename( "input.txt", "output.txt" );
  Rename( "docs", "mydocs" );
  Rename( "/input.txt", "/output.txt" ); # assuming permissions in /
  Rename( "/docs", "/mydocs" )           # assuming permissions in /
end use:


SetDirectory[NotebookDirectory[]]
RenameFile["input.txt", "output.txt"]
RenameDirectory["docs", "mydocs"]
SetDirectory[$RootDirectory]
RenameFile["input.txt", "output.txt"]
RenameDirectory["docs", "mydocs"]


[STATUS, MSG, MSGID] = movefile (F1, F2);


-- Here
renameFile "input.txt" "output.txt"
-- Root
renameFile "/input.txt" "/output.txt"


:- module rename_file.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.

:- import_module dir.

main(!IO) :-
    rename_file("input.txt", "output.txt", !IO),
    rename_file("docs", "mydocs", !IO),
    rename_file("/input.txt", "/output.txt", !IO),
    rename_file("/docs", "/mydocs", !IO).

:- pred rename_file(string::in, string::in, io::di, io::uo) is det.

rename_file(OldName, NewName, !IO) :-
    io.rename_file(OldName, NewName, Result, !IO),
    (
        Result = ok
    ;
        Result = error(Error),
        print_io_error(Error, !IO)
    ).

:- pred print_io_error(io.error::in, io::di, io::uo) is det.

print_io_error(Error, !IO) :-
   io.stderr_stream(Stderr, !IO),
   io.write_string(Stderr, io.error_message(Error), !IO),
   io.nl(Stderr, !IO),
   io.set_exit_status(1, !IO).


 ;Local
 S X=$ZF(-1,"rename input.txt output.txt")
 S X=$ZF(-1,"rename docs.dir mydocs.dir")
  ;Root of current device
 S X=$ZF(-1,"rename [000000]input.txt [000000]output.txt")
 S X=$ZF(-1,"rename [000000]docs.dir [000000]mydocs.dir")


#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

/* The language task, implemented with pthreads for POSIX systems. */

/* Each rendezvous_t will be accepted by a single thread, and entered
 * by one or more threads.  accept_func() only returns an integer and
 * is always run within the entering thread's context to simplify
 * handling the arguments and return value.  This somewhat unlike an
 * Ada rendezvous and is a subset of the Ada rendezvous functionality.
 * Ada's in and out parameters can be simulated via the void pointer
 * passed to accept_func() to update variables owned by both the
 * entering and accepting threads, if a suitable struct with pointers
 * to those variables is used. */
typedef struct rendezvous {
    pthread_mutex_t lock;        /* A mutex/lock to use with the CVs.        */
    pthread_cond_t cv_entering;  /* Signaled when a thread enters.           */
    pthread_cond_t cv_accepting; /* Signaled when accepting thread is ready. */
    pthread_cond_t cv_done;      /* Signaled when accept_func() finishes.    */
    int (*accept_func)(void*);   /* The function to run when accepted.       */
    int entering;                /* Number of threads trying to enter.       */
    int accepting;               /* True if the accepting thread is ready.   */
    int done;                    /* True if accept_func() is done.           */
} rendezvous_t;

/* Static initialization for rendezvous_t. */
#define RENDEZVOUS_INITILIZER(accept_function) {   \
        .lock         = PTHREAD_MUTEX_INITIALIZER, \
        .cv_entering  = PTHREAD_COND_INITIALIZER,  \
        .cv_accepting = PTHREAD_COND_INITIALIZER,  \
        .cv_done      = PTHREAD_COND_INITIALIZER,  \
        .accept_func  = accept_function,           \
        .entering     = 0,                         \
        .accepting    = 0,                         \
        .done         = 0,                         \
    }

int enter_rendezvous(rendezvous_t *rv, void* data)
{
    /* Arguments are passed in and out of the rendezvous via
     * (void*)data, and the accept_func() return value is copied and
     * returned to the caller (entering thread).  A data struct with
     * pointers to variables in both the entering and accepting
     * threads can be used to simulate Ada's in and out parameters, if
     * needed. */
    pthread_mutex_lock(&rv->lock);

    rv->entering++;
    pthread_cond_signal(&rv->cv_entering);

    while (!rv->accepting) {
        /* Nothing is accepting yet, keep waiting.  pthreads will
         * queue all waiting entries.  The loop is needed to handle
         * both race conditions and spurious wakeups. */
        pthread_cond_wait(&rv->cv_accepting, &rv->lock);
    }

    /* Call accept_func() and copy the return value before leaving
     * the mutex. */
    int ret = rv->accept_func(data);

    /* This signal is needed so that the accepting thread will wait
     * for the rendezvous to finish before trying to accept again. */
    rv->done = 1;
    pthread_cond_signal(&rv->cv_done);

    rv->entering--;
    rv->accepting = 0;
    pthread_mutex_unlock(&rv->lock);

    return ret;
}

void accept_rendezvous(rendezvous_t *rv)
{
    /* This accept function does not take in or return parameters.
     * That is handled on the entry side.  This is only for
     * synchronization. */
    pthread_mutex_lock(&rv->lock);
    rv->accepting = 1;

    while (!rv->entering) {
        /* Nothing to accept yet, keep waiting. */
        pthread_cond_wait(&rv->cv_entering, &rv->lock);
    }

    pthread_cond_signal(&rv->cv_accepting);

    while (!rv->done) {
        /* Wait for accept_func() to finish. */
        pthread_cond_wait(&rv->cv_done, &rv->lock);
    }
    rv->done = 0;

    rv->accepting = 0;
    pthread_mutex_unlock(&rv->lock);
}

/* The printer use case task implemented using the above rendezvous
 * implementation.  Since C doesn't have exceptions, return values are
 * used to signal out of ink errors. */

typedef struct printer {
    rendezvous_t rv;
    struct printer *backup;
    int id;
    int remaining_lines;
} printer_t;

typedef struct print_args {
    struct printer *printer;
    const char* line;
} print_args_t;

int print_line(printer_t *printer, const char* line) {
    print_args_t args;
    args.printer = printer;
    args.line = line;
    return enter_rendezvous(&printer->rv, &args);
}

int accept_print(void* data) {
    /* This is called within the rendezvous, so everything is locked
     * and okay to modify. */
    print_args_t *args = (print_args_t*)data;
    printer_t *printer = args->printer;
    const char* line = args->line;

    if (printer->remaining_lines) {
        /* Print the line, character by character. */
        printf("%d: ", printer->id);
        while (*line != '\0') {
            putchar(*line++);
        }
        putchar('\n');
        printer->remaining_lines--;
        return 1;
    }
    else if (printer->backup) {
        /* "Requeue" this rendezvous with the backup printer. */
        return print_line(printer->backup, line);
    }
    else {
        /* Out of ink, and no backup available. */
        return -1;
    }
}

printer_t backup_printer = {
    .rv = RENDEZVOUS_INITILIZER(accept_print),
    .backup = NULL,
    .id = 2,
    .remaining_lines = 5,
};

printer_t main_printer = {
    .rv = RENDEZVOUS_INITILIZER(accept_print),
    .backup = &backup_printer,
    .id = 1,
    .remaining_lines = 5,
};

void* printer_thread(void* thread_data) {
    printer_t *printer = (printer_t*) thread_data;
    while (1) {
        accept_rendezvous(&printer->rv);
    }
}

typedef struct poem {
    char* name;
    char* lines[];
} poem_t;

poem_t humpty_dumpty = {
    .name = "Humpty Dumpty",
    .lines = {
        "Humpty Dumpty sat on a wall.",
        "Humpty Dumpty had a great fall.",
        "All the king's horses and all the king's men",
        "Couldn't put Humpty together again.",
        ""
    },
};

poem_t mother_goose = {
    .name = "Mother Goose",
    .lines = {
        "Old Mother Goose",
        "When she wanted to wander,",
        "Would ride through the air",
        "On a very fine gander.",
        "Jack's mother came in,",
        "And caught the goose soon,",
        "And mounting its back,",
        "Flew up to the moon.",
        ""
    },
};

void* poem_thread(void* thread_data) {
    poem_t *poem = (poem_t*)thread_data;

    for (unsigned i = 0; poem->lines[i] != ""; i++) {
        int ret = print_line(&main_printer, poem->lines[i]);
        if (ret < 0) {
            printf("      %s out of ink!\n", poem->name);
            exit(1);
        }
    }
    return NULL;
}

int main(void)
{
    pthread_t threads[4];

    pthread_create(&threads[0], NULL, poem_thread,    &humpty_dumpty);
    pthread_create(&threads[1], NULL, poem_thread,    &mother_goose);
    pthread_create(&threads[2], NULL, printer_thread, &main_printer);
    pthread_create(&threads[3], NULL, printer_thread, &backup_printer);

    pthread_join(threads[0], NULL);
    pthread_join(threads[1], NULL);
    pthread_cancel(threads[2]);
    pthread_cancel(threads[3]);

    return 0;
}


$ include "seed7_05.s7i";

const func integer: repeatLength (in string: text) is func
  result
    var integer: length is 0;
  local
    var integer: pos is 0;
  begin
    for pos range succ(length(text) div 2) downto 1 until length <> 0 do
      if startsWith(text, text[pos ..]) then
        length := pred(pos);
      end if;
    end for;
  end func;

const proc: main is func
  local
    var string: line is "";
    var integer: length is 0;
  begin
    for line range [] ("1001110011", "1110111011", "0010010010", "1010101010",
                       "1111111111", "0100101101", "0100100", "101", "11", "00", "1") do
      length := repeatLength(line);
      if length = 0 then
        writeln("No rep-string for " <& literal(line));
      else
        writeln("Longest rep-string for " <& literal(line) <& ": " <& literal(line[.. length]));
      end if;
    end for;
  end func;


/* NetRexx */
options replace format comments java crossref symbols binary

runSample(arg)
return

-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
method isFileRenamed(oldFile, newFile) public static returns boolean
  fo = File(oldFile)
  fn = File(newFile)
  fRenamed = fo.renameTo(fn)
  return fRenamed

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  parse arg files
  if files = '' then files = 'input.txt output.txt F docs mydocs D /input.txt /output.txt F /docs /mydocs D'
  loop while files.length > 0
    parse files of nf ft files
    select case(ft.upper())
      when 'F' then do
        ft = 'File'
        end
      when 'D' then do
        ft = 'Directory'
        end
      otherwise do
        ft = 'File'
        end
      end
    if isFileRenamed(of, nf) then dl = 'renamed'
    else                          dl = 'not renamed'
    say ft ''''of'''' dl 'to' nf
    end

  return


(rename-file "./input.txt" "./output.txt")
(rename-file "./docs" "./mydocs")
(rename-file "/input.txt" "/output.txt")
(rename-file "/docs" "/mydocs")


import os

moveFile("input.txt", "output.txt")
moveFile("docs", "mydocs")

moveFile(DirSep & "input.txt", DirSep & "output.txt")
moveFile(DirSep & "docs", DirSep & "mydocs")


use IO;
bundle Default {
  class FileExample {
    function : Main(args : String[]) ~ Nil {
      File->Rename("input.txt", "output.txt");
      File->Rename("docs", "mydocs");
      File->Rename("/input.txt", "/output.txt");
      File->Rename("/docs", "/mydocs");
    }
  }
}


import std.stdio, std.array, std.datetime, std.exception,
       std.concurrency, core.thread, core.atomic;

final class OutOfInk: Exception {
    this() pure nothrow {
        super("Out of ink.");
    }
}

struct Printer {
    string id;
    size_t ink;

    void printIt(in string line) {
        enforce(ink != 0, new OutOfInk);
        writefln("%s: %s", id, line);
        ink--;
    }
}

/// Treats shared lvalue as if it is thread-local.
ref assumeThreadLocal(T)(ref shared T what) pure nothrow {
    return *cast(T*)&what;
}

struct RendezvousPrinter {
    Printer[] printers;

    void print(const(string)[] lines) shared {
        OutOfInk savedException;

        // Lightweight mutual exclusion
        // using shared atomic bool.
        shared static bool mutex;

        void lock() {
            while (!cas(&mutex, false, true))
                Thread.sleep(1.hnsecs);
        }

        void unlock() nothrow {
            assert(mutex.atomicLoad!(MemoryOrder.acq));
            mutex.atomicStore!(MemoryOrder.rel)(false);
        }

        while (!lines.empty) {
            if (printers.empty) {
                // No more printers to try.
                assert(savedException !is null);
                throw savedException;
            }

            try {
                {
                    lock;
                    scope(exit) unlock;
                    printers.front.assumeThreadLocal
                        .printIt(lines.front);
                }
                lines.popFront;

                // Increase the chance of interleaved output.
                Thread.sleep(10.msecs);
            } catch (OutOfInk exc) {
                savedException = exc;

                // Switch to the next printer.
                lock;
                scope(exit) unlock;
                printers.assumeThreadLocal.popFront;
            }
        }
    }
}

void humptyDumptyTask(shared ref RendezvousPrinter rendezvous) {
    const humptyDumpty = [
        "Humpty Dumpty sat on a wall.",
        "Humpty Dumpty had a great fall.",
        "All the king's horses and all the king's men,",
        "Couldn't put Humpty together again."];

    rendezvous.print(humptyDumpty);
}

void motherGooseTask(shared ref RendezvousPrinter rendezvous) {
    const motherGoose = ["Old Mother Goose,",
                         "When she wanted to wander,",
                         "Would ride through the air,",
                         "On a very fine gander.",
                         "Jack's mother came in,",
                         "And caught the goose soon,",
                         "And mounting its back,",
                         "Flew up to the moon."];

    rendezvous.print(motherGoose);
}

void main() {
    shared rendezvous = RendezvousPrinter
        ([Printer("main", 5), Printer("reserve", 5)]);

    spawn(&humptyDumptyTask, rendezvous);
    spawn(&motherGooseTask, rendezvous);
}


* Rep-string
	strings = "1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 "
	pat1 = (len(1) $ fc breakx(*fc)) $ x *x (arbno(*x) (rpos(0) | rem $ y *?(x ? y)))
getstring
	strings ? (break(" ") . rs len(1)) = :f(end)
	rs ? pat1 :s(yes)
	output = rs " is not a rep-string -> n/a" :(getstring)
yes
	output = rs " has shortest rep-string value of -> " x
	:(getstring)
end


import Foundation

func repString(_ input: String) -> [String] {
  return (1..<(1 + input.count / 2)).compactMap({x -> String? in
    let i = input.index(input.startIndex, offsetBy: x)
    return input.hasPrefix(input[i...]) ? String(input.prefix(x)) : nil
  })
}

let testCases = """
                1001110011
                1110111011
                0010010010
                1010101010
                1111111111
                0100101101
                0100100
                101
                11
                00
                1
                """.components(separatedBy: "\n")

for testCase in testCases {
  print("\(testCase) has reps: \(repString(testCase))")
}


proc repstring {text} {
    set len [string length $text]
    for {set i [expr {$len/2}]} {$i > 0} {incr i -1} {
	set sub [string range $text 0 [expr {$i-1}]]
	set eq [string repeat $sub [expr {int(ceil($len/double($i)))}]]
	if {[string equal -length $len $text $eq]} {
	    return $sub
	}
    }
    error "no repetition"
}


  ( reverse
  = L x
    .     :?L
        & @( !arg
           :   ?
               ( %?x
               & utf$!x
               & !x !L:?L
               & ~`
               )
               ?
           )
      | str$!L
  )
& out$reverse$Ελληνικά


NSFileManager *fm = [NSFileManager defaultManager];

// Pre-OS X 10.5
[fm movePath:@"input.txt" toPath:@"output.txt" handler:nil];
[fm movePath:@"docs" toPath:@"mydocs" handler:nil];

// OS X 10.5+
[fm moveItemAtPath:@"input.txt" toPath:@"output.txt" error:NULL];
[fm moveItemAtPath:@"docs" toPath:@"mydocs" error:NULL];


let () =
  Sys.rename "input.txt" "output.txt";
  Sys.rename "docs" "mydocs";
  Sys.rename "/input.txt" "/output.txt";
  Sys.rename "/docs" "/mydocs";


OS-RENAME "input.txt" "output.txt".
OS-RENAME "docs" "mydocs".

OS-RENAME "/input.txt" "/output.txt".
OS-RENAME "/docs" "/mydocs".


system("mv input.txt output.txt");
system("mv /input.txt /output.txt");
system("mv docs mydocs");
system("mv /docs /mydocs");


-module( rendezvous ).

-export( [task/0] ).

task() ->
    Printer_pid = erlang:spawn( fun() -> printer(1, 5) end ),
    Reserve_printer_pid = erlang:spawn( fun() -> printer(2, 5) end ),
    Monitor_pid = erlang:spawn( fun() -> printer_monitor(Printer_pid, Reserve_printer_pid) end ),
    erlang:spawn( fun() -> print(Monitor_pid, humpty_dumpty()) end ),
    erlang:spawn( fun() -> print(Monitor_pid, mother_goose()) end ).

humpty_dumpty() ->
        ["Humpty Dumpty sat on a wall.",
                "Humpty Dumpty had a great fall.",
                "All the king's horses and all the king's men,",
                "Couldn't put Humpty together again."].

mother_goose() ->
        ["Old Mother Goose,",
               "When she wanted to wander,",
               "Would ride through the air,",
               "On a very fine gander.",
               "Jack's mother came in,",
               "And caught the goose soon,",
               "And mounting its back,",
               "Flew up to the moon."].

print( Pid, Lines ) ->
    io:fwrite( "Print ~p started~n", [erlang:self()] ),
    print( Pid, Lines, infinity ).

print( _Pid, [], _Timeout ) -> ok;
print( Pid, [Line | T], Timeout ) ->
    print_line( Pid, Line, Timeout ),
    print_line_done(),
    print( Pid, T, Timeout ).

print_line( Pid, Line, Timeout ) ->
    Pid ! {print, Line, erlang:self()},
    receive
    {print, started} -> ok
    after Timeout -> erlang:throw( timeout )
    end.

print_line_done() ->
    receive
    {printer, ok} -> ok;
    {printer, out_of_ink} -> erlang:throw( out_of_ink )
    end.

printer( N, 0 ) ->
        receive
        {print, _Line, Pid} -> Pid ! {printer, out_of_ink}
        end,
        printer( N, 0 );
printer( N, Ink ) ->
        receive
        {print, Line, Pid} ->
                Pid ! {printer, ok},
                io:fwrite( "~p: ", [N] ),
                [io:fwrite("~c", [X]) || X <- Line],
                io:nl()
        end,
        printer( N, Ink - 1 ).

printer_monitor( Printer, Reserve ) ->
        {Line, Pid} = printer_monitor_get_line(),
        Result = printer_monitor_print_line( Printer, Line ),
        printer_monitor_reserve( Result, Reserve, Line, Pid ),
        printer_monitor( Printer, Reserve ).

printer_monitor_get_line() ->
        receive
        {print, Line, Pid} ->
                Pid ! {print, started},
                {Line, Pid}
        end.

printer_monitor_print_line( Printer_pid, Line ) ->
        Printer_pid ! {print, Line, erlang:self()},
        receive
        {printer, Result} -> Result
        end.

printer_monitor_reserve( ok, _Reserve_pid, _Line, Pid ) -> Pid ! {printer, ok};
printer_monitor_reserve( out_of_ink, Reserve_pid, Line, Pid ) -> Reserve_pid ! {print, Line, Pid}.


is_repeated() {
    local str=$1 len rep part
    for (( len = ${#str} / 2; len > 0; len-- )); do
        part=${str:0:len}
        rep=""
        while (( ${#rep} < ${#str} )); do
            rep+=$part
        done
        if [[ ${rep:0:${#str}} == $str ]] && (( $len < ${#str} )); then
            echo "$part"
            return 0
        fi
    done
    return 1
}

while read test; do
    if part=$( is_repeated "$test" ); then
        echo "$test is composed of $part repeated"
    else
        echo "$test is not a repeated string"
    fi
done <<END_TESTS
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
END_TESTS


Function rep_string(s)
	max_len = Int(Len(s)/2)
	tmp = ""
	If max_len = 0 Then
		rep_string = "No Repeating String"
		Exit Function
	End If
	For i = 1 To max_len
		If InStr(i+1,s,tmp & Mid(s,i,1))Then
			tmp = tmp & Mid(s,i,1)
		Else
			Exit For
		End If
	Next
	Do While Len(tmp) > 0
		If Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then
			rep_string = tmp
			Exit Do
		Else
			tmp = Mid(tmp,1,Len(tmp)-1)
		End If
	Loop
	If Len(tmp) > 0 Then
		rep_string = tmp
	Else
		rep_string = "No Repeating String"
	End If
End Function

'testing the function
arr = Array("1001110011","1110111011","0010010010","1010101010",_
		"1111111111","0100101101","0100100","101","11","00","1")

For n = 0 To UBound(arr)
	WScript.StdOut.Write arr(n) & ": " & rep_string(arr(n))
	WScript.StdOut.WriteLine
Next


  var
    f : file ; // Untyped file
 begin

  // as current directory
  AssignFile(f,'input.doc');
  Rename(f,'output.doc');

  // as root directory
  AssignFile(f,'\input.doc');
  Rename(f,'\output.doc');

  // rename a directory
  AssignFile(f,'docs');
  Rename(f,'mydocs');

  //rename a directory off the root

  AssignFile(f,'\docs');
  Rename(f,'\mydocs');

end;


use File::Copy qw(move);
use File::Spec::Functions qw(catfile rootdir);
# here
move 'input.txt', 'output.txt';
move 'docs', 'mydocs';
# root dir
move (catfile rootdir, 'input.txt'), (catfile rootdir, 'output.txt');
move (catfile rootdir, 'docs'), (catfile rootdir, 'mydocs');


without js -- (file i/o)
?rename_file("input.txt","output.txt")
?rename_file("docs","mydocs")
?rename_file("C:\\Copy.txt","Copy.xxx")
?rename_file("C:\\docs","C:\\mydocs")


_platform "windows" == if "\\" "ren " else "/" "mv " endif
var com var slash

com "input.txt output.txt" chain cmd
com "docs mydocs" chain cmd
com slash chain "input.txt " chain slash chain "output.txt" chain cmd
com slash chain "docs " chain slash chain "mydocs" chain cmd


<?php
rename('input.txt', 'output.txt');
rename('docs', 'mydocs');
rename('/input.txt', '/output.txt');
rename('/docs', '/mydocs');
?>


open System

type PrinterCommand = Print of string

// a message is a command and a facility to return an exception
type Message = Message of PrinterCommand * AsyncReplyChannel<Exception option>

// thrown if we have no more ink (and neither has our possible backup printer)
exception OutOfInk

type Printer(id, ?backup:Printer) =
   let mutable ink = 5

   // the actual printing logic as a private function
   let print line =
      if ink > 0 then
         printf "%d: " id
         Seq.iter (printf "%c") line
         printf "\n"
         ink <- ink - 1
      else
         match backup with
         | Some p -> p.Print line
         | None -> raise OutOfInk

   // use a MailboxProcessor to process commands asynchronously;
   // if an exception occurs, we return it to the calling thread
   let agent = MailboxProcessor.Start( fun inbox ->
      async {
         while true do
            let! Message (command, replyChannel) = inbox.Receive()
            try
               match command with
               | Print line -> print line
               replyChannel.Reply None
            with
               | ex -> replyChannel.Reply (Some ex)
      })

   // public printing method:
   // send Print command and propagate exception if one occurs
   member x.Print line =
      match agent.PostAndReply( fun replyChannel -> Message (Print line, replyChannel) ) with
      | None -> ()
      | Some ex -> raise ex

open System.Threading

do
  let main = new Printer(id=1, backup=new Printer(id=2))

  (new Thread(fun () ->
      try
        main.Print "Humpty Dumpty sat on a wall."
        main.Print "Humpty Dumpty had a great fall."
        main.Print "All the king's horses and all the king's men"
        main.Print "Couldn't put Humpty together again."
      with
        | OutOfInk -> printfn "      Humpty Dumpty out of ink!"
  )).Start()

  (new Thread(fun () ->
      try
        main.Print "Old Mother Goose"
        main.Print "Would ride through the air"
        main.Print "On a very fine gander."
        main.Print "Jack's mother came in,"
        main.Print "And caught the goose soon,"
        main.Print "And mounting its back,"
        main.Print "Flew up to the moon."
      with
        | OutOfInk -> printfn "      Mother Goose out of ink!"
  )).Start()

  Console.ReadLine() |> ignore


package main

import (
    "errors"
    "fmt"
    "strings"
    "sync"
)

var hdText = `Humpty Dumpty sat on a wall.
Humpty Dumpty had a great fall.
All the king's horses and all the king's men,
Couldn't put Humpty together again.`

var mgText = `Old Mother Goose,
When she wanted to wander,
Would ride through the air,
On a very fine gander.
Jack's mother came in,
And caught the goose soon,
And mounting its back,
Flew up to the moon.`

func main() {
    reservePrinter := startMonitor(newPrinter(5), nil)
    mainPrinter := startMonitor(newPrinter(5), reservePrinter)
    var busy sync.WaitGroup
    busy.Add(2)
    go writer(mainPrinter, "hd", hdText, &busy)
    go writer(mainPrinter, "mg", mgText, &busy)
    busy.Wait()
}

// printer is a type representing an abstraction of a physical printer.
// It is a type defintion for a function that takes a string to print
// and returns an error value, (hopefully usually nil, meaning no error.)
type printer func(string) error

// newPrinter is a constructor.  The parameter is a quantity of ink.  It
// returns a printer object encapsulating the ink quantity.
// Note that this is not creating the monitor, only the object serving as
// a physical printer by writing to standard output.
func newPrinter(ink int) printer {
    return func(line string) error {
        if ink == 0 {
            return eOutOfInk
        }
        for _, c := range line {
            fmt.Printf("%c", c)
        }
        fmt.Println()
        ink--
        return nil
    }
}

var eOutOfInk = errors.New("out of ink")

// For the language task, rSync is a type used to approximate the Ada
// rendezvous mechanism that includes the caller waiting for completion
// of the callee.  For this use case, we signal completion with an error
// value as a response.  Exceptions are not idiomatic in Go and there is
// no attempt here to model the Ada exception mechanism.  Instead, it is
// idomatic in Go to return error values.  Sending an error value on a
// channel works well here to signal completion.  Go unbuffered channels
// provide synchronous rendezvous, but call and response takes two channels,
// which are bundled together here in a struct.  The channel types are chosen
// to mirror the parameter and return types of "type printer" defined above.
// The channel types here, string and error are both "reference types"
// in Go terminology.  That is, they are small things containing pointers
// to the actual data.  Sending one on a channel does not involve copying,
// or much less marshalling string data.
type rSync struct {
    call     chan string
    response chan error
}

// "rendezvous Print" requested by use case task.
// For the language task though, it is implemented here as a method on
// rSync that sends its argument on rSync.call and returns the result
// received from rSync.response.  Each channel operation is synchronous.
// The two operations back to back approximate the Ada rendezvous.
func (r *rSync) print(data string) error {
    r.call <- data      // blocks until data is accepted on channel
    return <-r.response // blocks until response is received
}

// monitor is run as a goroutine.  It encapsulates the printer passed to it.
// Print requests are received through the rSync object "entry," named entry
// here to correspond to the Ada concept of an entry point.
func monitor(hardPrint printer, entry, reserve *rSync) {
    for {
        // The monitor goroutine will block here waiting for a "call"
        // to its "entry point."
        data := <-entry.call
        // Assuming the call came from a goroutine calling rSync.print,
        // that goroutine is now blocked, waiting for this one to send
        // a response.

        // attempt output
        switch err := hardPrint(data); {

        // consider return value from attempt
        case err == nil:
            entry.response <- nil // no problems

        case err == eOutOfInk && reserve != nil:
            // Requeue to "entry point" of reserve printer monitor.
            // Caller stays blocked, and now this goroutine blocks until
            // it gets a response from the reserve printer monitor.
            // It then transparently relays the response to the caller.
            entry.response <- reserve.print(data)

        default:
            entry.response <- err // return failure
        }
        // The response is away.  Loop, and so immediately block again.
    }
}

// startMonitor can be seen as an rSync constructor.  It also
// of course, starts the monitor for which the rSync serves as entry point.
// Further to the langauge task, note that the channels created here are
// unbuffered.  There is no buffer or message box to hold channel data.
// A sender will block waiting for a receiver to accept data synchronously.
func startMonitor(p printer, reservePrinter *rSync) *rSync {
    entry := &rSync{make(chan string), make(chan error)}
    go monitor(p, entry, reservePrinter)
    return entry
}

// Two writer tasks are started as goroutines by main.  They run concurrently
// and compete for printers as resources.  Note the call to "rendezvous Print"
// as requested in the use case task and compare the syntax,
//    Here:           printMonitor.print(line);
//    Ada solution:   Main.Print ("string literal");
func writer(printMonitor *rSync, id, text string, busy *sync.WaitGroup) {
    for _, line := range strings.Split(text, "\n") {
        if err := printMonitor.print(line); err != nil {
            fmt.Printf("**** writer task %q terminated: %v ****\n", id, err)
            break
        }
    }
    busy.Done()
}


import "/fmt" for Fmt

var repString = Fn.new { |s|
    var reps = []
    if (s.count < 2) return reps
    for (c in s) if (c != "0" && c != "1") Fiber.abort("Argument is not a binary string.")
    var size = s.count
    for (len in 1..(size/2).floor) {
        var t = s[0...len]
        var n = (size/len).floor
        var r = size % len
        var u = t * n + t[0...r]
        if (u == s) reps.add(t)
    }
    return reps
}

var strings = [
    "1001110011",
    "1110111011",
    "0010010010",
    "1010101010",
    "1111111111",
    "0100101101",
    "0100100",
    "101",
    "11",
    "00",
    "1"
]
System.print("The (longest) rep-strings are:\n")
for (s in strings) {
    var reps = repString.call(s)
    var t = (reps.count > 0) ? reps[-1] : "Not a rep-string"
    Fmt.print("$10s -> $s", s, t)
}


#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>

const char *sa = "abcdef";
const char *su = "as⃝df̅"; /* Should be in your native locale encoding. Mine is UTF-8 */

int is_comb(wchar_t c)
{
	if (c >= 0x300 && c <= 0x36f) return 1;
	if (c >= 0x1dc0 && c <= 0x1dff) return 1;
	if (c >= 0x20d0 && c <= 0x20ff) return 1;
	if (c >= 0xfe20 && c <= 0xfe2f) return 1;
	return 0;
}

wchar_t* mb_to_wchar(const char *s)
{
	wchar_t *u;
	size_t len = mbstowcs(0, s, 0) + 1;
	if (!len) return 0;

	u = malloc(sizeof(wchar_t) * len);
	mbstowcs(u, s, len);
	return u;
}

wchar_t* ws_reverse(const wchar_t* u)
{
	size_t len, i, j;
	wchar_t *out;
	for (len = 0; u[len]; len++);
	out = malloc(sizeof(wchar_t) * (len + 1));
	out[len] = 0;
	j = 0;
	while (len) {
		for (i = len - 1; i && is_comb(u[i]); i--);
		wcsncpy(out + j, u + i, len - i);
		j += len - i;
		len = i;
	}
	return out;
}

char *mb_reverse(const char *in)
{
	size_t len;
	char *out;
	wchar_t *u = mb_to_wchar(in);
	wchar_t *r = ws_reverse(u);
	len = wcstombs(0, r, 0) + 1;
	out = malloc(len);
	wcstombs(out, r, len);
	free(u);
	free(r);
	return out;
}

int main(void)
{
	setlocale(LC_CTYPE, "");

	printf("%s => %s\n", sa, mb_reverse(sa));
	printf("%s => %s\n", su, mb_reverse(su));
	return 0;
}


(call 'mv "input.txt" "output.txt")
(call 'mv "docs" "mydocs")
(call 'mv "/input.txt" "/output.txt")
(call 'mv "/docs" "/mydocs")


int main(){
   mv("input.txt", "output.txt");
   mv("/input.txt", "/output.txt");
   mv("docs", "mydocs");
   mv("/docs", "/mydocs");
}


sys_file_move('inputs.txt', 'output.txt');
sys_file_move('docs', 'mydocs');
sys_file_move('/inputs.txt', '/output.txt');
sys_file_move(/'docs', '/mydocs');


Rename-Item input.txt output.txt

# The Rename-item has the alias ren
ren input.txt output.txt


void setup(){
  boolean sketchfile = rename(sketchPath("input.txt"), sketchPath("output.txt"));
  boolean sketchfold = rename(sketchPath("docs"), sketchPath("mydocs"));
  // sketches will seldom have write permission to root files/folders
  boolean rootfile = rename("input.txt", "output.txt");
  boolean rootfold = rename("docs", "mydocs");
  // true if succeeded, false if failed
  println(sketchfile, sketchfold, rootfile, rootfold);
}

boolean rename(String oldname, String newname) {
  // File (or directory) with old name
  File file = new File(oldname);
  // File (or directory) with new name
  File file2 = new File(newname);
  // Rename file (or directory)
  boolean success = file.renameTo(file2);
  return success;
}


rename input.txt to output.txt
rename docs to mydocs


RenameFile("input.txt", "output.txt")
RenameFile("docs\", "mydocs\")

RenameFile("/input.txt","/output.txt")
RenameFile("/docs\","/mydocs\")


mutable struct Printer
    inputpath::Channel{String}
    errorpath::Channel{String}
    inkremaining::Int32
    reserve::Printer
    name::String
    function Printer(ch1, ch2, ink, name)
        this = new()
        this.inputpath = ch1
        this.errorpath = ch2
        this.inkremaining = ink
        this.name = name
        this.reserve = this
        this
    end
end

function lineprintertask(printer)
    while true
        line = take!(printer.inputpath)
        linesprinted = 0
        if(printer.inkremaining < 1)
            if(printer.reserve == printer)
                put!(printer.errorpath, "Error: printer $(printer.name) out of ink")
            else
                put!(printer.reserve.inputpath, line)
            end
        else
            println(line)
            printer.inkremaining -= 1
        end
    end
end

function schedulework(poems)
    printerclose(printer) = (close(printer.inputpath); close(printer.errorpath))
    reserveprinter = Printer(Channel{String}(1), Channel{String}(10), 5, "Reserve")
    mainprinter = Printer(Channel{String}(1), Channel{String}(10), 5, "Main")
    mainprinter.reserve = reserveprinter
    @async(lineprintertask(mainprinter))
    @async(lineprintertask(reserveprinter))
    printers = [mainprinter, reserveprinter]
    activeprinter = 1
    @sync(
    for poem in poems
        activeprinter = (activeprinter % length(printers)) + 1
        @async(
        for line in poem
            put!(printers[activeprinter].inputpath, line)
        end)
    end)
    for p in printers
        while isready(p.errorpath)
            println(take!(p.errorpath))
        end
        printerclose(p)
    end
end

const humptydumpty = ["Humpty Dumpty sat on a wall.",
                      "Humpty Dumpty had a great fall.",
                      "All the king's horses and all the king's men,",
                      "Couldn't put Humpty together again."]

const oldmothergoose = ["Old Mother Goose,",
                        "When she wanted to wander,",
                        "Would ride through the air,",
                        "On a very fine gander.",
                        "Jack's mother came in,",
                        "And caught the goose soon,",
                        "And mounting its back,",
                        "Flew up to the moon."]

schedulework([humptydumpty, oldmothergoose])


import asyncdispatch, options, strutils
type
  Printer = ref object
    inkLevel, id: int
    backup: Option[Printer]
  OutOfInkException = object of IOError
proc print(p: Printer, line: string){.async.} =
  if p.inkLevel <= 0:
    if p.backup.isNone():
      raise newException(OutOfInkException, "out of ink")
    else:
      await p.backup.get().print(line)
  else:
    p.inkLevel-=1
    stdout.writeLine("$1:$2".format(p.id, line))
    await sleepAsync(100)
proc newPrinter(inkLevel, id: int, backup: Option[Printer]): Printer =
  new(result)
  result.inkLevel = inkLevel
  result.id = id
  result.backup = backup

proc print(p: Printer, msg: seq[string]){.async.} =
  for line in msg:
    try:
      await p.print(line)
    except OutOfInkException as e:
      echo("out of ink")
      break
const
  humptyLines = @[
    "Humpty Dumpty sat on a wall.",
    "Humpty Dumpty had a great fall.",
    "All the king's horses and all the king's men,",
    "Couldn't put Humpty together again.",
    ]
  gooseLines = @[
        "Old Mother Goose,",
        "When she wanted to wander,",
        "Would ride through the air,",
        "On a very fine gander.",
        "Jack's mother came in,",
        "And caught the goose soon,",
        "And mounting its back,",
        "Flew up to the moon.",
    ]
proc main(){.async.} =
  var
    reservePrinter = newPrinter(5, 2, none(Printer))
    mainPrinter = newPrinter(5, 1, some(reservePrinter))
  await mainPrinter.print(gooseLines) and mainPrinter.print(humptyLines)

waitFor main()


declare
  class Printer
     attr ink:5

     feat id backup

     meth init(id:ID backup:Backup<=unit)
        self.id = ID
        self.backup = Backup
     end

     meth print(Line)=Msg
        if @ink == 0 then
           if self.backup == unit then
              raise outOfInk end
           else
              {self.backup Msg}
           end
        else
           {System.printInfo self.id#": "}
           for C in Line do
              {System.printInfo [C]}
           end
           {System.printInfo "\n"}
           ink := @ink - 1
        end
     end
  end


without js -- (threads)
constant print_cs = init_cs()
enum NAME,INK
sequence printers = {{"main",5},
                     {"reserve",5}}

procedure printer(string name, sequence s)
    try
        for i=1 to length(s) do
            enter_cs(print_cs)
            for p=1 to length(printers) do
                if printers[p][INK]!=0 then
                    printers[p][INK] -= 1
                    printf(1,"%s/%s: %s\n",{name,printers[p][NAME],s[i]})
                    exit
                elsif p=length(printers) then
                    throw("out of ink")
                end if
            end for
            leave_cs(print_cs)
        end for
        exit_thread(0)
    catch e
        printf(1,"exception(%s): %s\n",{name,e[E_USER]})
        leave_cs(print_cs)
        exit_thread(1)
    end try
end procedure

constant hd = {"Humpty Dumpty sat on a wall.",
               "Humpty Dumpty had a great fall.",
               "All the king's horses and all the king's men",
               "Couldn't put Humpty together again."},
         mg = {"Old Mother Goose",
               "When she wanted to wander,",
               "Would ride through the air",
               "On a very fine gander.",
               "Jack's mother came in,",
               "And caught the goose soon,",
               "And mounting its back,",
               "Flew up to the moon."}

sequence hThreads = {create_thread(printer,{"hd",hd}),
                     create_thread(printer,{"mg",mg})}
wait_thread(hThreads)


fcn repString(s){
   foreach n in ([s.len()/2+1..1,-1]){
      Walker.cycle(s[0,n]).pump(s.len(),String) :
      if(_==s and n*2<=s.len()) return(n);
   }
   return(False)
}


static string ReverseString(string input)
{
    char[] inputChars = input.ToCharArray();
    Array.Reverse(inputChars);
    return new string(inputChars);
}


#include <iostream>
#include <string>
#include <algorithm>

int main()
{
  std::string s;
  std::getline(std::cin, s);
  std::reverse(s.begin(), s.end()); // modifies s
  std::cout << s << std::endl;
  return 0;
}


import os

os.rename("input.txt", "output.txt")
os.rename("docs", "mydocs")

os.rename(os.sep + "input.txt", os.sep + "output.txt")
os.rename(os.sep + "docs", os.sep + "mydocs")


  $ "
import os
if os.path.exists('input.txt'):
    os.rename('input.txt', 'output.txt')
" python

  $ "
import os
if os.path.exists('docs'):
    os.rename('docs', 'mydocs')
" python

  $ "
import os
if os.path.exists('/input.txt'):
    os.rename('/input.txt', '/output.txt')
" python

  $ "
import os
if os.path.exists('/docs'):
    os.rename('/docs', '/mydocs')
" python


#lang racket

(rename-file-or-directory "input.txt" "output.txt")
(rename-file-or-directory "docs" "mydocs")

;; find the filesystem roots, and pick the first one
(define root (first (filesystem-root-list)))

(rename-file-or-directory (build-path root "input.txt")
                          (build-path root "output.txt"))
(rename-file-or-directory (build-path root "docs")
                          (build-path root "mydocs"))


rename 'input.txt', 'output.txt';
rename 'docs', 'mydocs';
rename '/input.txt', '/output.txt';
rename '/docs', '/mydocs';


`mv /path/to/file/oldfile /path/to/file/newfile` shell


Sub Renamer()
    Dim f As FolderItem, r As FolderItem

    f = GetFolderItem("input.txt")
    'Changing a FolderItem's Name attribute renames the file or directory.
    If f.Exists Then f.Name = "output.txt"
    'Files and directories are handled almost identically in RB.
    f = GetFolderItem("docs")
    If f.Exists Then f.Name = "mydocs"

    'Jump through hoops to find the root directory.
    r = RootDir(GetFolderItem("."))

    f = r.Child("input.txt")
    'Renaming in a different directory identical to renaming in current directory.
    If f.Exists Then f.Name = "output.txt"
    f = r.Child("docs")
    If f.Exists Then f.Name = "mydocs"
End Sub

Function RootDir(what As FolderItem) As FolderItem
    'RB doesn't have an easy way to find the root of the current drive;
    'not an issue under *nix but troublesome under Windows.
    If what.Parent <> Nil Then  'Nil = no parent = root.
        Return RootDir(what.Parent) 'Recursive.
    Else
        Return what
    End If
End Function


(de rendezvous (Pid . Exe)
   (when
      (catch '(NIL)
         (tell Pid 'setq 'Rendezvous (lit (eval Exe)))
         NIL )
      (tell Pid 'quit @) ) )  # Raise caught error in caller


"""An approximation of the rendezvous pattern found in Ada using asyncio."""
from __future__ import annotations

import asyncio
import sys

from typing import Optional
from typing import TextIO

class OutOfInkError(Exception):
    """Exception raised when a printer is out of ink."""

class Printer:
    def __init__(self, name: str, backup: Optional[Printer]):
        self.name = name
        self.backup = backup

        self.ink_level: int = 5
        self.output_stream: TextIO = sys.stdout

    async def print(self, msg):
        if self.ink_level <= 0:
            if self.backup:
                await self.backup.print(msg)
            else:
                raise OutOfInkError(self.name)
        else:
            self.ink_level -= 1
            self.output_stream.write(f"({self.name}): {msg}\n")

async def main():
    reserve = Printer("reserve", None)
    main = Printer("main", reserve)

    humpty_lines = [
        "Humpty Dumpty sat on a wall.",
        "Humpty Dumpty had a great fall.",
        "All the king's horses and all the king's men,",
        "Couldn't put Humpty together again.",
    ]

    goose_lines = [
        "Old Mother Goose,",
        "When she wanted to wander,",
        "Would ride through the air,",
        "On a very fine gander.",
        "Jack's mother came in,",
        "And caught the goose soon,",
        "And mounting its back,",
        "Flew up to the moon.",
    ]

    async def print_humpty():
        for line in humpty_lines:
            try:
                task = asyncio.Task(main.print(line))
                await task
            except OutOfInkError:
                print("\t Humpty Dumpty out of ink!")
                break

    async def print_goose():
        for line in goose_lines:
            try:
                task = asyncio.Task(main.print(line))
                await task
            except OutOfInkError:
                print("\t Mother Goose out of ink!")
                break

    await asyncio.gather(print_goose(), print_humpty())

if __name__ == "__main__":
    asyncio.run(main(), debug=True)


#lang racket

;;; Rendezvous primitives implemented in terms of synchronous channels.
(define (send ch msg)
  (define handshake (make-channel))
  (channel-put ch (list msg handshake))
  (channel-get handshake)
  (void))

(define (receive ch action)
  (match-define (list msg handshake) (channel-get ch))
  (action msg)
  (channel-put handshake 'done))

;;; A printer receives a line of text, then
;;;   - prints it                      (still ink left)
;;;   - sends it to the backup printer (if present)
;;;   - raises exception               (if no ink and no backup)
(define (printer id ink backup)
  (define (on-line-received line)
    (cond
      [(and (= ink 0) (not backup)) (raise 'out-of-ink)]
      [(= ink 0)                    (send backup line)]
      [else                         (display (~a id ":"))
                                    (for ([c line]) (display c))
                                    (newline)]))
  (define ch (make-channel))
  (thread
   (λ ()
    (let loop ()
      (receive ch on-line-received)
      (set! ink (max 0 (- ink 1)))
      (loop))))
  ch)

;;; Setup two printers

(define reserve (printer "reserve" 5 #f))
(define main    (printer "main"    5 reserve))

;;; Two stories

(define humpty
  '("Humpty Dumpty sat on a wall."
	"Humpty Dumpty had a great fall."
	"All the king's horses and all the king's men,"
	"Couldn't put Humpty together again."))

(define goose
  '("Old Mother Goose,"
    "When she wanted to wander,"
    "Would ride through the air,"
	"On a very fine gander."
	"Jack's mother came in,"
	"And caught the goose soon,"
	"And mounting its back,"
	"Flew up to the moon."))

;;; Print the stories
(for ([l humpty]) (send main l))
(for ([l goose])  (send main l))


USER>Write $Reverse("Hello, World")

dlroW ,olleH


shared void run() {

   while(true) {
      process.write("> ");
      String? text = process.readLine();
      if (is String text) {
      print(text.reversed);
      }
      else {
      break;
      }
    }
}


rename %input.txt %output.txt
rename %docs/ %mydocs/

; Unix. Note that there's no path specification used for the
; new name. "Rename" is not "move".

rename %/input.txt %output.txt
rename %/docs/ %mydocs/

; DOS/Windows:

rename %/c/input.txt %output.txt
rename %/c/docs/ %mydocs/

; Because REBOL treats data access schemes as uniformly as possible,
; you can do tricks like this:

rename ftp://username:password@ftp.site.com/www/input.txt %output.txt
rename ftp://username:password@ftp.site.com/www/docs/ %mydocs/


/*REXX program renames a file & a directory  (in current dir & in root).*/
trace off                              /*suppress error messages, bad RC*/

    do 2                               /* [↓]  perform this code twice. */
    'RENAME' "input.txt  output.txt"   /*rename a particular DOS file.  */
    'MOVE'   "\docs  \mydocs"          /*use (DOS) MOVE to rename a dir.*/
    'CD'     "\"                       /*for 2nd pass, change──►root dir*/
    end   /*2*/
                                       /*stick a fork in it, we're done.*/


  rename("input.txt", "output.txt")
  rename("docs", "mydocs")
  rename("/input.txt", "/output.txt")
  rename("/docs", "/mydocs")


File.rename('input.txt', 'output.txt')
File.rename('/input.txt', '/output.txt')
File.rename('docs', 'mydocs')
File.rename('/docs', '/mydocs')


a$ = shell$("RENAME input.txt output.txt")
a$ = shell$("RENAME docs mydocs")
a$ = shell$("RENAME \input.txt \output.txt")
a$ = shell$("RENAME \docs \mydocs")


class X::OutOfInk is Exception {
    method message() { "Printer out of ink" }
}

class Printer {
    has Str      $.id;
    has Int      $.ink = 5;
    has Lock     $!lock .= new;
    has ::?CLASS $.fallback;

    method print ($line) {
        $!lock.protect: {
            if    $!ink      { say "$!id: $line"; $!ink-- }
            elsif $!fallback { $!fallback.print: $line }
            else             { die X::OutOfInk.new }
        }
    }
}

my $printer =
    Printer.new: id => 'main', fallback =>
    Printer.new: id => 'reserve';

sub client ($id, @lines) {
    start {
        for @lines {
            $printer.print: $_;
            CATCH {
                when X::OutOfInk { note "<$id stops for lack of ink>"; exit }
            }
        }
        note "<$id is done>";
    }
}

await
    client('Humpty', q:to/END/.lines),
        Humpty Dumpty sat on a wall.
        Humpty Dumpty had a great fall.
        All the king's horses and all the king's men,
        Couldn't put Humpty together again.
        END
    client('Goose', q:to/END/.lines);
        Old Mother Goose,
        When she wanted to wander,
        Would ride through the air,
        On a very fine gander.
        Jack's mother came in,
        And caught the goose soon,
        And mounting its back,
        Flew up to the moon.
        END


package require Tcl 8.6
package require Thread

# Really ought to go in a package
eval [set rendezvousEngine {
array set Select {w {} c 0}

# Turns the task into a coroutine, making it easier to write in "Ada style".
# The real thread ids are stored in shared variables.
proc task {id script} {
    global rendezvousEngine
    set task [list coroutine RTask eval "$script;thread::exit"]
    tsv::set tasks $id [thread::create \
		"$rendezvousEngine;$task;thread::wait"]
}

# A simple yielding pause.
proc pause t {
    after $t [info coroutine]
    yield
}

# Wait for a message. Note that this is *not* pretty code and doesn't do
# everything that the Ada rendezvous does.
proc select args {
    global Select
    set var [namespace which -variable Select](m[incr Select(c)])
    set messages {}
    foreach {message vars body} $args {
	dict set messages $message $body
	dict set bindings $message $vars
    }
    lappend Select(w) [list $var [dict keys $messages]]
    try {
	set Master ""
	while {$Master eq ""} {
	    set Master [yield]
	}
	lassign $Master message responder payload
	foreach vbl [dict get $bindings $message] value $payload {
	    upvar 1 $vbl v
	    set v $value
	}
	set body [dict get $messages $message]
	set code [uplevel 1 [list catch $body ::Select(em) ::Select(op)]]
	set opts $Select(op)
	if {$code == 1} {
	    dict append opts -errorinfo \
		"\n    while processing message\n$message $payload"
	}
	set $responder [list $code $Select(em) $opts]
    } finally {
	catch {unset $var}
	set Select(w) [lrange $Select(w) 0 end-1]
    }
}

# This acts as a receiver for messages, feeding them into the waiting
# [select].  It is incomplete as it should (but doesn't) queue messages that
# can't be received currently.
proc receive {message args} {
    global Select
    lassign [lindex $Select(w) end] var messages
    if {$message ni $messages} {
	throw BAD_MESSAGE "don't know message $message"
    }
    set responder [namespace which -variable Select](r[incr Select(c)])
    set $responder ""
    RTask [list $message $responder $args]
    set response [set $responder]
    unset responder
    after 1
    return $response
}

# This dispatches a message to a task in another thread.
proc send {target message args} {
    after 1
    set t [tsv::get tasks $target]
    if {![thread::send $t [list receive $message {*}$args] response]} {
	lassign $response code msg opts
	return -options $opts $msg
    } else {
	return -code error $response
    }
}
}]

# The backup printer task.
task BackupPrinter {
    set n 5
    while {$n >= 0} {
	select Print msg {
	    if {$n > 0} {
		incr n -1
		puts Backup:$msg
	    } else {
		throw OUT_OF_INK "out of ink"
	    }
	}
    }
}

# The main printer task.
task MainPrinter {
    set n 5
    set Backup BackupPrinter
    while 1 {
	select Print msg {
	    try {
		if {$n > 0} {
		    incr n -1
		    puts Main:$msg
		} elseif {$Backup ne ""} {
		    send $Backup Print $msg
		} else {
		    throw OUT_OF_INK "out of ink"
		}
	    } trap OUT_OF_INK {} {
		set Backup ""
		throw OUT_OF_INK "out of ink"
	    }
	}
    }
}

# Tasks that generate messages to print.
task HumptyDumpty {
    pause 100
    try {
	send MainPrinter Print "Humpty Dumpty sat on a wall."
	send MainPrinter Print "Humpty Dumpty had a great fall."
	send MainPrinter Print "All the King's horses and all the King's men"
	send MainPrinter Print "Couldn't put Humpty together again."
    } trap OUT_OF_INK {} {
	puts "Humpty Dumpty out of ink!"
    }
}
task MotherGoose {
    pause 100
    try {
	send MainPrinter Print "Old Mother Goose"
	send MainPrinter Print "When she wanted to wander,"
	send MainPrinter Print "Would ride through the air"
	send MainPrinter Print "On a very fine gander."
	send MainPrinter Print "Jack's mother came in,"
	send MainPrinter Print "And caught the goose soon,"
	send MainPrinter Print "And mounting its back,"
	send MainPrinter Print "Flew up to the moon."
    } trap OUT_OF_INK {} {
	puts "Mother Goose out of ink!"
    }
}

# Wait enough time for the example to run and then finish
after 1000
thread::broadcast thread::exit


FUNCTION Reverse(sIn)
   LOCAL sOut := "", i
   FOR i := Len(sIn) TO 1 STEP -1
      sOut += Substr(sIn, i, 1)
   NEXT
RETURN sOut


(defn reverse-string [s]
  "Returns a string with all characters in reverse"
  (apply str (reduce conj '() s)))


use std::fs;

fn main() {
    let err = "File move error";
    fs::rename("input.txt", "output.txt").ok().expect(err);
    fs::rename("docs", "mydocs").ok().expect(err);
    fs::rename("/input.txt", "/output.txt").ok().expect(err);
    fs::rename("/docs", "/mydocs").ok().expect(err);
}


import scala.language.implicitConversions
import java.io.File

object Rename0 {
  def main(args: Array[String]) {              // The implicit causes every String to File mapping,
    implicit def file(s: String) = new File(s) // will be converted to new File(String)
    "myfile.txt" renameTo "anotherfile.txt"
    "/tmp/myfile.txt" renameTo "/tmp/anotherfile.txt"
    "mydir" renameTo "anotherdir"
    "/tmp/mydir" renameTo "/tmp/anotherdir"
  }
}


(rename-file "input.txt" "output.txt")
(rename-file "docs" "mydocs")
(rename-file "/input.txt" "/output.txt")
(rename-file "/docs" "/mydocs")


$ include "seed7_05.s7i";
  include "osfiles.s7i";

const proc: main is func
  begin
    moveFile("input.txt", "output.txt");
    moveFile("docs", "mydocs");
    moveFile("/input.txt", "/output.txt");
    moveFile("/docs", "/mydocs");
  end func;


# Here
File.rename('input.txt', 'output.txt');
File.rename('docs',      'mydocs');

# Root dir
File.rename(Dir.root + %f'input.txt', Dir.root + %f'output.txt');
File.rename(Dir.root + %f'docs',      Dir.root + %f'mydocs');


class Printer {
    construct new(id, ink) {
        _id = id
        _ink = ink
    }

    ink     { _ink }
    ink=(v) { _ink = v }

    print(text) {
        System.write("%(_id): ")
        for (c in text) System.write(c)
        System.print()
        _ink = _ink - 1
    }
}

var ptrMain    = Printer.new("Main   ", 5)
var ptrReserve = Printer.new("Reserve", 5)

var hd = [
    "Humpty Dumpty sat on a wall.",
    "Humpty Dumpty had a great fall.",
    "All the king's horses and all the king's men",
    "Couldn't put Humpty together again."
]

var mg = [
    "Old Mother Goose",
    "When she wanted to wander,",
    "Would ride through the air",
    "On a very fine gander.",
    "Jack's mother came in,",
    "And caught the goose soon,",
    "And mounting its back,",
    "Flew up to the moon."
]

var task = Fn.new { |name|
    var lines = (name == "Humpty Dumpty") ? hd : mg
    for (line in lines) {
        if (ptrMain.ink > 0) {
            ptrMain.print(line)
            Fiber.yield()
        } else if (ptrReserve.ink > 0) {
            ptrReserve.print(line)
            Fiber.yield()
        } else {
            Fiber.abort("ERROR  : Reserve printer ran out of ink in %(name) task.")
        }
    }
}

var rhymes = ["Humpty Dumpty", "Mother Goose"]
var tasks = List.filled(2, null)
for (i in 0..1) {
   tasks[i] = Fiber.new(task)
   tasks[i].call(rhymes[i])
}

while (true) {
    for (i in 0..1) {
        if (!tasks[i].isDone) {
            var error = tasks[i].try()
            if (error) {
                System.print(error)
                return
            }
        }
    }
    if (tasks.all { |task| task.isDone }) return
}


class OutOfInk(Exception.IOError){
   const TEXT="Out of ink";
   text=TEXT;	// rename IOError to OutOfInk for this first/mother class
   fcn init{ IOError.init(TEXT) }  // this renames instances
}
class Printer{
   var id, ink;
   fcn init(_id,_ink){ id,ink=vm.arglist }
   fcn print(line){
      if(not ink) throw(OutOfInk);
      println("%s: %s".fmt(id,line));
      Atomic.sleep((0.0).random(0.01));  // don't let one thread dominate
      ink-=1;
   }
}
class RendezvousPrinter{  // the choke point between printers and tasks
   var printers=Thread.List();  // a thread safe list
   fcn init(_printers){ printers.extend(vm.arglist) }
   fcn print(line){  // caller waits for print job to finish
      var lines=Thread.List(); // fcn local [static] variable, the print queue
      lines.write(line);	// thread safe, stalls when full
      // lines is racy - other threads are modifing it, length is suspect here
      while(True){  // this thread can print that threads job
	 critical{  // creates a [global] mutex, automatically unlocks on exception
	    if(not printers) throw(OutOfInk); // No more printers to try
	    if(not lines) break; // only remove jobs in this serialized section
	    try{
	       printers[0].print(lines[0]);  // can throw
	       lines.del(0);  // successful print, remove job from queue
	    }catch(OutOfInk){ printers.del(0) } // Switch to the next printer
	 }
      }
   }
}


reverse = proc (s: string) returns (string)
    rslt: array[char] := array[char]$predict(1,string$size(s))
    for c: char in string$chars(s) do
        array[char]$addl(rslt,c)
    end
    return(string$ac2s(rslt))
end reverse

start_up = proc ()
    po: stream := stream$primary_output()
    stream$putl(po, reverse("!dlrow ,olleH"))
end start_up


(File newNamed: 'input.txt') renameTo: 'output.txt'.
(File newNamed: '/input.txt') renameTo: '/output.txt'.
(Directory newNamed: 'docs') renameTo: 'mydocs'.
(Directory newNamed: '/docs') renameTo: '/mydocs'.


File rename: 'input.txt' to: 'output.txt'.
File rename: 'docs' to: 'mydocs'.
"as for other example, this works on systems
 where the root is / ..."
File rename: '/input.txt' to: '/output.txt'.
File rename: '/docs' to: '/mydocs'


OS.FileSys.rename {old = "input.txt", new = "output.txt"};
OS.FileSys.rename {old = "docs", new = "mydocs"};
OS.FileSys.rename {old = "/input.txt", new = "/output.txt"};
OS.FileSys.rename {old = "/docs", new = "/mydocs"};


!ren input.txt output.txt
!ren docs mydocs


file rename inputs.txt output.txt
file rename docs mydocs

file rename [file nativename /inputs.txt] [file nativename /output.txt]
file rename [file nativename /docs] [file nativename /mydocs]


needs shell
" input.txt"  " output.txt"  rename
" /input.txt"  " /output.txt"  rename

" docs"  " mydocs"  rename
" /docs"  " /mydocs"  rename


fileCopy("Input.txt", "Output.txt");
fileDelete("Input.txt");

for(%File = FindFirstFile("Path/*.*"); %File !$= ""; %File = FindNextFile("Path/*.*"))
{
	fileCopy(%File, "OtherPath/" @ %File);
	fileDelete(%File);
}


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


$$ MODE TUSCRIPT
- rename file
ERROR/STOP RENAME ("input.txt","output.txt")
- rename directory
ERROR/STOP RENAME ("docs","mydocs",-std-)


(rename-path "input.txt" "output.txt")
;; Windows (MinGW based port)
(rename-path "C:\\input.txt" "C:\\output.txt")
;; Unix; Windows (Cygwin port)
(rename-path "/input.txt" "/output.txt"))


mv input.txt output.txt
mv /input.txt /output.txt
mv docs mydocs
mv /docs /mydocs


// In current directory
File_Rename("input.txt", "output.txt")
File_Rename("docs", "mydocs")

// In the root directory
File_Rename("/input.txt", "/output.txt")
File_Rename("/docs", "/mydocs")


'Current Directory
IO.Directory.Move("docs", "mydocs")
IO.File.Move("input.txt", "output.txt")

'Root
IO.Directory.Move("\docs", "\mydocs")
IO.File.Move("\input.txt", "\output.txt")

'Root, platform independent
IO.Directory.Move(IO.Path.DirectorySeparatorChar & "docs", _
 IO.Path.DirectorySeparatorChar & "mydocs")
IO.File.Move(IO.Path.DirectorySeparatorChar & "input.txt", _
  IO.Path.DirectorySeparatorChar & "output.txt")


import "/ioutil" for FileUtil

FileUtil.move("input.txt", "output.txt")
FileUtil.move("/input.txt", "/output.txt")


MODULE BbtReverseString;
IMPORT StdLog;

PROCEDURE ReverseStr(str: ARRAY OF CHAR): POINTER TO ARRAY OF CHAR;
VAR
	top,middle,i: INTEGER;
	c: CHAR;
	rStr: POINTER TO ARRAY OF CHAR;
BEGIN
	NEW(rStr,LEN(str$) + 1);
	top := LEN(str$) - 1; middle := (top - 1) DIV 2;
	FOR i := 0 TO middle DO
		rStr[i] := str[top - i];
		rStr[top - i] := str[i];
	END;
	IF ODD(LEN(str$)) THEN rStr[middle + 1] := str[middle + 1] END;
	RETURN rStr;
END ReverseStr;

PROCEDURE Do*;
VAR
	x: CHAR;
BEGIN
	StdLog.String("'asdf' reversed:> ");StdLog.String(ReverseStr("asdf"));StdLog.Ln
END Do;
END BbtReverseString.


if peek$("os") = "windows" then
    slash$ = "\\" : com$ = "ren "
else
    slash$ = "/" : com$ = "mv "
end if

system(com$ + "input.txt output.txt")
system(com$ + "docs mydocs")
system(com$ + slash$ + "input.txt " + slash$ + "output.txt")
system(com$ + slash$ + "docs " + slash$ + "mydocs")


rename, "input.txt", "output.txt";
rename, "/input.txt", "/output.txt";
rename, "docs", "mydocs";
rename, "/docs", "/mydocs";


ls -ld input.txt docs output.txt mydocs
ls: cannot access 'output.txt': No such file or directory
ls: cannot access 'mydocs': No such file or directory
drwxr-xr-x 2 craigd craigd 4096 Aug 10 16:24 docs
-rw-r--r-- 1 craigd craigd    0 Aug 10 16:24 input.txt
$ zkl
zkl: File.rename("input.txt","output.txt")
True
zkl: File.rename("docs","mydocs")
True
zkl: ^D
$ ls -ld input.txt docs output.txt mydocs
ls: cannot access 'input.txt': No such file or directory
ls: cannot access 'docs': No such file or directory
drwxr-xr-x 2 craigd craigd 4096 Aug 10 16:24 mydocs
-rw-r--r-- 1 craigd craigd    0 Aug 10 16:24 output.txt


include "cowgol.coh";
include "strings.coh";

# Reverse a string in place
sub StrRev(s: [uint8]): (r: [uint8]) is
    r := s;
    var e := s;
    while [e] != 0 loop
        e := @next e;
    end loop;
    e := @prev e;
    while e > s loop
        var c := [s];
        [s] := [e];
        [e] := c;
        s := @next s;
        e := @prev e;
    end loop;
end sub;

# Test
var buf: uint8[32];
var str: [uint8] := "\nesreveR";
CopyString(str, &buf[0]);
print(StrRev(&buf[0]));


# version 0.21.1

strings = ["asdf", "as⃝df̅"]
strings.each do |s|
  puts "#{s} -> #{s.reverse}"
end


void main() {
	import std.range, std.conv;

	string s1 = "hello"; // UTF-8
	assert(s1.retro.text == "olleh");

	wstring s2 = "hello"w; // UTF-16
	assert(s2.retro.wtext == "olleh"w);

	dstring s3 = "hello"d; // UTF-32
	assert(s3.retro.dtext == "olleh"d);

	// without using std.range:
	dstring s4 = "hello"d;
	assert(s4.dup.reverse == "olleh"d); // simple but inefficient (copies first, then reverses)
}


String reverse(String s) => new String.fromCharCodes(s.runes.toList().reversed);


K=
STR_OUT=
FOR J=%TRIM(STR_IN) STEP -1 UNTIL 1
DO BEGIN
      INCR K
      STR_OUT(K:1)=STR_IN(J:1)
   END


function ReverseString(const InString: string): string;
var
  i: integer;
begin
  for i := Length(InString) downto 1 do
    Result := Result + InString[i];
end;


let str = "asdf"

func String.Reverse() {
    var cs = []
    let len = this.Length()
    for n in 1..len {
        cs.Add(this[len - n])
    }
    String(values: cs)
}

str.Reverse()


pragma.enable("accumulator")
def reverse(string) {
  return accum "" for i in (0..!(string.size())).descending() { _ + string[i] }
}


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

(string-reverse "ghij")
    → jihg
(string-reverse "un roc lamina l animal cornu")
    → unroc lamina l animal cor nu


function reverse( str string ) returns( string )
	result string;
	for ( i int from StrLib.characterLen( str ) to 1 decrement by 1 )
		result ::= str[i:i];
	end
	return( result );
end


class
    APPLICATION
create
    make
feature
    make
            -- Demonstrate string reversal.
        do
            my_string := "Hello World!"
            my_string.mirror
            print (my_string)
        end
    my_string: STRING
            -- Used for reversal
end


reverse_string str = rev len str
  where len = length str
        rev 0 str = ""
        rev n str = toString (str : nn) +> rev nn str
          where nn = n - 1

reverse_string "Hello"


import system'routines;
import extensions;
import extensions'text;

extension extension
{
    reversedLiteral()
        = self.toArray().sequenceReverse().summarize(new StringWriter());
}

public program()
{
    console.printLine("Hello World".reversedLiteral())
}


IO.puts (String.reverse "asdf")
IO.puts (String.reverse "as⃝df̅")


-- The import on the next line provides the reverse string
-- functionality satisfying the rosettacode.org task description.
import String exposing (reverse)

-- The rest is fairly boilerplate code demonstrating
-- interactively that the reverse function works.
import Html exposing (Html, Attribute, text, div, input)
import Html.Attributes exposing (placeholder, value, style)
import Html.Events exposing (on, targetValue)
import Html.App exposing (beginnerProgram)

main = beginnerProgram { model = "", view = view, update = update }

update newStr oldStr = newStr

view : String -> Html String
view forward =
  div []
    ([ input
        [ placeholder "Enter a string to be reversed."
        , value forward
        , on "input" targetValue
        , myStyle
        ]
        []
     ] ++
     [ let backward = reverse forward
       in div [ myStyle] [text backward]
     ])

myStyle : Attribute msg
myStyle =
  style
    [ ("width", "100%")
    , ("height", "20px")
    , ("padding", "5px 0 0 5px")
    , ("font-size", "1em")
    , ("text-align", "left")
    ]


PROGRAM REVERSE_STRING

PROCEDURE REVERSE(A$->R$)
   LOCAL I%
   R$=""
   FOR I=1 TO LEN(A$) DO
     R$=MID$(A$,I,1)+R$
   END FOR
END PROCEDURE

BEGIN
   A$="THE FIVE BOXING WIZARDS JUMP QUICKLY"
   REVERSE(A$->R$)
   PRINT(R$)
END PROGRAM


>function strrev (s) := chartostr(fliplr(strtochar(s)))
>strrev("This is a test!")
 !tset a si sihT


include std/sequence.e
printf(1, "%s\n", {reverse("abcdef") })


## இந்த நிரல் தரப்படும் சரம் ஒன்றைத் தலைகீழாகத் திருப்பி அச்சிடும்
## உதாரணமாக "abc" என்ற சரம் தரப்பட்டால் அதனைத் திருப்பி "cba" என அச்சிடும்
## "எழில்" மொழியின்மூலம் இரண்டு வகைகளில் இதனைச் செய்யலாம். இரண்டு உதாரணங்களும் இங்கே தரப்பட்டுள்ளன

நிரல்பாகம் திருப்புக (சரம்1)

    ## முதல் வகை

    சரம்2 = ""

    @( சரம்1  இல் இ) ஒவ்வொன்றாக
          சரம்2 =  இ + சரம்2
        முடி

    பின்கொடு சரம்2

முடி

நிரல்பாகம் மீண்டும்திருப்புக (சரம்1)

    ## இரண்டாம் வகை

    சரநீளம் = len(சரம்1)

    சரம்2 = ""

    @(எண் = 0, எண் < சரநீளம், எண் = எண் + 1) ஆக

      சரம்2 = எடு(சரம்1, எண்) + சரம்2

    முடி

    பின்கொடு சரம்2

முடி

அ = உள்ளீடு("ஓர் எழுத்துச் சரத்தைத் தாருங்கள் ")

பதிப்பி "நீங்கள் தந்த எழுத்துச் சரம்" அ

பதிப்பி "அதனை முதல் வகையில் திருப்பியுள்ளோம்: " திருப்புக(அ)

பதிப்பி "வேறொரு வகையில் திருப்பியுள்ளோம்: " மீண்டும்திருப்புக(அ)


// Reverse a string. Nigel Galloway: August 14th., 2019
let strRev α=let N=System.Globalization.StringInfo.GetTextElementEnumerator(α)
             List.unfold(fun n->if n then Some(N.GetTextElement(),N.MoveNext()) else None)(N.MoveNext())|>List.rev|>String.concat ""


FUNCTION StrRev1(BYVAL $p1)
	DIM $b = ""
	REPEAT LEN(p1)
		b = b & RIGHT(p1,1)
		p1 = LEFT(p1,LEN(p1)-1)
	END REPEAT
	RETURN b
END FUNCTION


: exchange ( a1 a2 -- )
  2dup [email protected] swap [email protected] rot c! swap c! ;
: reverse ( c-addr u -- )
  1- bounds begin 2dup > while
    2dup exchange
    -1 /string
  repeat 2drop ;

s" testing" 2dup reverse type   \ gnitset


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


' FB 1.05.0 Win64

Function ReverseString(s As Const String) As String
  If s = "" Then Return s
  Dim length As Integer = Len(s)
  Dim r As String = Space(length)
  For i As Integer = 0 To length - 1
     r[i] = s[length - 1 - i]
  Next
  Return r
End Function

Dim s As String = "asdf"
Print "'"; s; "' reversed is '"; ReverseString(s); "'"


void local fn DoIt
  CFStringRef s1 = @"asdf", s2 = @""
  long index
  for index = len(s1) - 1 to 0 step -1
    s2 = fn StringByAppendingString( s2, mid(s1,index,1) )
  next
  print s1,s2
end fn

window 1

fn DoIt

HandleEvents


Public Sub Main()
Dim sString As String = "asdf"
Dim sOutput As String
Dim siCount As Short

For siCount = Len(sString) DownTo 1
  sOutput &= Mid(sString, siCount, 1)
Next

Print sOutput

End


[indent=4]
/*
   Reverse a string, in Genie
   valac reverse.gs
*/

init
    utf8:string = "asdf"
    combining:string = "asdf̅"

    print utf8
    print utf8.reverse()

    print combining
    print combining.reverse()


PRINT @reverse$("asdf")
'
FUNCTION reverse$(string$)
  LOCAL result$,i%
  result$=""
  FOR i%=1 TO LEN(string$)
    result$=MID$(string$,i%,1)+result$
  NEXT i%
  RETURN result$
ENDFUNC


package main

import (
    "fmt"
    "unicode"
    "unicode/utf8"
)

// no encoding
func reverseBytes(s string) string {
    r := make([]byte, len(s))
    for i := 0; i < len(s); i++ {
        r[i] = s[len(s)-1-i]
    }
    return string(r)
}

// reverseCodePoints interprets its argument as UTF-8 and ignores bytes
// that do not form valid UTF-8.  return value is UTF-8.
func reverseCodePoints(s string) string {
    r := make([]rune, len(s))
    start := len(s)
    for _, c := range s {
        // quietly skip invalid UTF-8
        if c != utf8.RuneError {
            start--
            r[start] = c
        }
    }
    return string(r[start:])
}

// reversePreservingCombiningCharacters interprets its argument as UTF-8
// and ignores bytes that do not form valid UTF-8.  return value is UTF-8.
func reversePreservingCombiningCharacters(s string) string {
    if s == "" {
        return ""
    }
    p := []rune(s)
    r := make([]rune, len(p))
    start := len(r)
    for i := 0; i < len(p); {
        // quietly skip invalid UTF-8
        if p[i] == utf8.RuneError {
            i++
            continue
        }
        j := i + 1
        for j < len(p) && (unicode.Is(unicode.Mn, p[j]) ||
            unicode.Is(unicode.Me, p[j]) || unicode.Is(unicode.Mc, p[j])) {
            j++
        }
        for k := j - 1; k >= i; k-- {
            start--
            r[start] = p[k]
        }
        i = j
    }
    return (string(r[start:]))
}

func main() {
    test("asdf")
    test("as⃝df̅")
}

func test(s string) {
    fmt.Println("\noriginal:      ", []byte(s), s)
    r := reverseBytes(s)
    fmt.Println("reversed bytes:", []byte(r), r)
    fmt.Println("original code points:", []rune(s), s)
    r = reverseCodePoints(s)
    fmt.Println("reversed code points:", []rune(r), r)
    r = reversePreservingCombiningCharacters(s)
    fmt.Println("combining characters:", []rune(r), r)
}


println "Able was I, 'ere I saw Elba.".reverse()


FUNCTION Reverse( sIn )

   LOCAL cOut := "", i

   FOR i := Len( sIn ) TO 1 STEP -1
      cOut += Substr( sIn, i, 1 )
   NEXT

   RETURN cOut


CHARACTER string = "Hello World", tmp

L = LEN( string )
DO i = 1, L/2
  tmp = string(i)
  string(i) = string(L-i+1)
  string(L-i+1) = tmp
ENDDO

WRITE(Messagebox, Name) string


procedure main(arglist)
s := \arglist[1] | "asdf"
write(s," <-> ", reverse(s))    # reverse is built-in
end


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


//using chained methods
function reverseStr(s) {
  return s.split('').reverse().join('');
}

//fast method using for loop
function reverseStr(s) {
  for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]) { }
  return o;
}

//fast method using while loop (faster with long strings in some browsers when compared with for loop)
function reverseStr(s) {
  var i = s.length, o = '';
  while (i--) o += s[i];
  return o;
}


def reverse_string: explode | reverse | implode;


var str = "Never odd or even";
puts(str);
puts(str.split('').reverse().join(''));


fun main(args: Array<String>) {
    println("asdf".reversed())
}


(include "string" "algorithm")
(main
  (decl std::string s)
  (std::getline std::cin s)
  (std::reverse (s.begin) (s.end))
  (prn s))


{S.reverse hello brave new world}
-> world new brave hello


: flip "" split reverse "" join ;
"qwer asdf" flip .


writeln cp2s reverse s2cp q(don't you know)


        .ORIG      0x3000

        LEA        R1,STRING
        LEA        R2,GNIRTS
        LD         R3,MINUS1
        NOT        R5,R1
        ADD        R5,R5,1

SCAN    LDR        R4,R1,0
        BRZ        COPY
        ADD        R1,R1,1
        BRNZP      SCAN

COPY    ADD        R1,R1,R3
        ADD        R4,R1,R5
        BRN        COPIED
        LDR        R4,R1,0
        STR        R4,R2,0
        ADD        R2,R2,1
        BRNZP      COPY

COPIED  AND        R4,R4,0
        STR        R4,R2,0

        LEA        R0,GNIRTS
        PUTS

        HALT

MINUS1  .FILL      0xFFFF

STRING  .STRINGZ   "If thou beest he -- but O how fall'n! how chang'd"
GNIRTS  .BLKW      128

        .END


input$ ="abcdefgABCDEFG012345"
print input$
print ReversedStr$( input$)

end

function ReversedStr$(in$)
    for i =len(in$) to 1 step -1
    ReversedStr$ =ReversedStr$ +mid$( in$, i, 1)
    next i
end function


on reverse (str)
  res = ""
  repeat with i = str.length down to 1
    put str.char[i] after res
  end repeat
  return res
end


function reverseString S
   repeat with i = length(S) down to 1
      put char i of S after R
   end repeat
   return R
end reverseString


; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.

; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps

$"main.printf" = comdat any

@main.str = private unnamed_addr constant [12 x i8] c"Hello world\00", align 1
@"main.printf" = linkonce_odr unnamed_addr constant [4 x i8] c"%s\0A\00", comdat, align 1

define void @reverse(i64, i8*) {
  %3 = alloca i8*, align 8          ; allocate str (local)
  %4 = alloca i64, align 8          ; allocate len (local)
  %5 = alloca i64, align 8          ; allocate i
  %6 = alloca i64, align 8          ; allocate j
  %7 = alloca i8, align 1           ; allocate t
  store i8* %1, i8** %3, align 8    ; set str (local) to the parameter str
  store i64 %0, i64* %4, align 8    ; set len (local) to the paremeter len
  store i64 0, i64* %5, align 8     ; i = 0
  %8 = load i64, i64* %4, align 8   ; load len
  %9 = sub i64 %8, 1                ; decrement len
  store i64 %9, i64* %6, align 8    ; j =
  br label %loop

loop:
  %10 = load i64, i64* %5, align 8  ; load i
  %11 = load i64, i64* %6, align 8  ; load j
  %12 = icmp ult i64 %10, %11       ; i < j
  br i1 %12, label %loop_body, label %exit

loop_body:
  %13 = load i8*, i8** %3, align 8                  ; load str
  %14 = load i64, i64* %5, align 8                  ; load i
  %15 = getelementptr inbounds i8, i8* %13, i64 %14 ; address of str[i]
  %16 = load i8, i8* %15, align 1                   ; load str[i]
  store i8 %16, i8* %7, align 1                     ; t = str[i]
  %17 = load i64, i64* %6, align 8                  ; load j
  %18 = getelementptr inbounds i8, i8* %13, i64 %17 ; address of str[j]
  %19 = load i8, i8* %18, align 1                   ; load str[j]
  %20 = getelementptr inbounds i8, i8* %13, i64 %14 ; address of str[i]
  store i8 %19, i8* %20, align 1                    ; str[i] = str[j]
  %21 = load i8, i8* %7, align 1                    ; load t
  %22 = getelementptr inbounds i8, i8* %13, i64 %17 ; address of str[j]
  store i8 %21, i8* %22, align 1                    ; str[j] = t

;-- loop increment
  %23 = load i64, i64* %5, align 8  ; load i
  %24 = add i64 %23, 1              ; increment i
  store i64 %24, i64* %5, align 8   ; store i
  %25 = load i64, i64* %6, align 8  ; load j
  %26 = add i64 %25, -1             ; decrement j
  store i64 %26, i64* %6, align 8   ; store j
  br label %loop

exit:
  ret void
}

define i32 @main() {
;-- char str[]
  %1 = alloca [12 x i8], align 1
;-- memcpy(str, "Hello world")
  %2 = bitcast [12 x i8]* %1 to i8*
  call void @llvm.memcpy.p0i8.p0i8.i64(i8* %2, i8* getelementptr inbounds ([12 x i8], [12 x i8]* @main.str, i32 0, i32 0), i64 12, i32 1, i1 false)
;-- printf("%s\n", str)
  %3 = getelementptr inbounds [12 x i8], [12 x i8]* %1, i32 0, i32 0
  %4 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"main.printf", i32 0, i32 0), i8* %3)
;-- %7 = strlen(str)
  %5 = getelementptr inbounds [12 x i8], [12 x i8]* %1, i32 0, i32 0
  %6 = call i64 @strlen(i8* %5)
;-- reverse(%6, str)
  call void @reverse(i64 %6, i8* %5)
;-- printf("%s\n", str)
  %7 = getelementptr inbounds [12 x i8], [12 x i8]* %1, i32 0, i32 0
  %8 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"main.printf", i32 0, i32 0), i8* %7)
;-- end of main
  ret i32 0
}

;--- The declaration for the external C printf function.
declare i32 @printf(i8*, ...)

; Function Attrs: argmemonly nounwind
declare void @llvm.memcpy.p0i8.p0i8.i64(i8* nocapture writeonly, i8* nocapture readonly, i64, i32, i1)

declare i64 @strlen(i8*)


Module ReverseString {
      a$="as⃝df̅"
      Print Len(a$), len.disp(a$)
      Let i=1, j=Len(a$)
      z$=String$(" ",j)
      j++
      do {
            k$=mid$(a$, i, 1)
            if i<len(a$) then {
                  while len.disp(k$+mid$(a$, i+1,1)) =len.disp(k$)  {
                        k$+=mid$(a$, i+1,1)
                        i++
                        if i>len(a$) then exit
                        j--
                  }
                  j--
                  insert j, len(k$) Z$=K$
            } else j-- :Insert j,1 z$=k$
            if i>=len(a$) then exit
            i++
      } Always
      Print len(z$), len.disp(z$)
      Print z$="f̅ds⃝a"
      Print z$
}
ReverseString


(readlist (reverse (explode "my-string")))


> StringTools:-Reverse( "foo" );
                                 "oof"


>> fliplr(['She told me that she spoke English and I said great. '...
'Grabbed her hand out the club and I said let''s skate.'])

ans =

.etaks s'tel dias I dna bulc eht tuo dnah reh debbarG .taerg dias I dna hsilgnE ekops ehs taht em dlot ehS


sreverse("abcdef");         /* "fedcba" */

sreverse("rats live on no evil star");   /* not a bug :o) */


fn reverseString s =
(
    local reversed = ""
    for i in s.count to 1 by -1 do reversed += s[i]
    reversed
)


str = "This is a string"
print "Forward: " + str
newStr = ""
for i in range(str.len-1, 0)
    newStr = newStr + str[i]
end for
print "Reversed: " + newStr


# First, it gets the length of the original string
# Then, it allocates memory from the copy
# Then it copies the pointer to the original string, and adds the strlen
#     subtract 1, then that new pointer is at the last char.
# while(strlen)
#     copy char
#     decrement strlen
#     decrement source pointer
#     increment target pointer

.text

strcpy:
  addi $sp, $sp, -4
  sw $s0, 0($sp)
  add $s0, $zero, $zero

L1:
  add $t1, $s0, $a1
  lb $t2, 0($t1)
  add $t3, $s0, $a0
  sb $t2, 0($t3)
  beq $t2, $zero, L2
  addi $s0, $s0, 1
  j L1

L2:
  lw $s0, 0($sp)
  addi $sp, $sp, 4
  jr $ra

.data
	ex_msg_og: .asciiz "Original string:\n"
	ex_msg_cpy: .asciiz "\nCopied string:\n"
	string: .asciiz "Nice string you got there!\n"


def reverse(s:string)
    StringBuilder.new(s).reverse
end

puts reverse('reversed')


MODULE ReverseStr;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;

PROCEDURE WriteInt(n : INTEGER);
VAR buf : ARRAY[0..15] OF CHAR;
BEGIN
    FormatString("%i", buf, n);
    WriteString(buf)
END WriteInt;

PROCEDURE ReverseStr(in : ARRAY OF CHAR; VAR out : ARRAY OF CHAR);
VAR ip,op : INTEGER;
BEGIN
    ip := 0;
    op := 0;
    WHILE in[ip] # 0C DO
        INC(ip)
    END;
    DEC(ip);
    WHILE ip>=0 DO
        out[op] := in[ip];
        INC(op);
        DEC(ip)
    END
END ReverseStr;

TYPE A = ARRAY[0..63] OF CHAR;
VAR is,os : A;
BEGIN
    is := "Hello World";
    ReverseStr(is, os);

    WriteString(is);
    WriteLn;
    WriteString(os);
    WriteLn;

    ReadChar
END ReverseStr.


MODULE Reverse EXPORTS Main;

IMPORT IO, Text;

PROCEDURE String(item: TEXT): TEXT =
  VAR result: TEXT := "";
  BEGIN
    FOR i := Text.Length(item) - 1 TO 0 BY - 1 DO
      result := Text.Cat(result, Text.FromChar(Text.GetChar(item, i)));
    END;
    RETURN result;
  END String;

BEGIN
  IO.Put(String("Foobarbaz") & "\n");
END Reverse.


REVERSE
 ;Take in a string and reverse it using the built in function $REVERSE
 NEW S
 READ:30 "Enter a string: ",S
 WRITE !,$REVERSE(S)
 QUIT


def reverse(string)
        l = ""

        for char in list(str(string)).reverse()
                l += char
        end

        return l
end


/* Reverse a string, in Neko */

var reverse = function(s) {
  var len = $ssize(s)
  if len < 2 return s

  var reverse = $smake(len)
  var pos = 0
  while len > 0 $sset(reverse, pos ++= 1, $sget(s, len -= 1))
  return reverse
}

var str = "never odd or even"
$print(str, "\n")
$print(reverse(str), "\n\n")

str = "abcdefghijklmnopqrstuvwxyz"
$print(str, "\n")
$print(reverse(str), "\n\n")

$print("single test\n")
str = "a"
$print(str, "\n")
$print(reverse(str), "\n\n")

$print("empty test\n")
str = ""
$print(str, "\n")
$print(reverse(str), "\n")


/* NetRexx */

options replace format comments java crossref savelog symbols nobinary

reverseThis = 'asdf'
sihTesrever = reverseThis.reverse

say reverseThis
say sihTesrever

return


import unicode

proc reverse(s: var string) =
  for i in 0 .. s.high div 2:
    swap(s[i], s[s.high - i])

proc reversed(s: string): string =
  result = newString(s.len)
  for i,c in s:
    result[s.high - i] = c

proc uniReversed(s: string): string =
  result = newStringOfCap(s.len)
  var tmp: seq[Rune] = @[]
  for r in runes(s):
    tmp.add(r)
  for i in countdown(tmp.high, 0):
    result.add(toUtf8(tmp[i]))

proc isComb(r: Rune): bool =
  (r >=% Rune(0x300) and r <=% Rune(0x36f)) or
    (r >=% Rune(0x1dc0) and r <=% Rune(0x1dff)) or
    (r >=% Rune(0x20d0) and r <=% Rune(0x20ff)) or
    (r >=% Rune(0xfe20) and r <=% Rune(0xfe2f))

proc uniReversedPreserving(s: string): string =
  result = newStringOfCap(s.len)
  var tmp: seq[Rune] = @[]
  for r in runes(s):
    if isComb(r): tmp.insert(r, tmp.high)
    else: tmp.add(r)
  for i in countdown(tmp.high, 0):
    result.add(toUtf8(tmp[i]))

for str in ["Reverse This!", "as⃝df̅"]:
  echo "Original string:       ", str
  echo "Reversed:              ", reversed(str)
  echo "UniReversed:           ", uniReversed(str)
  echo "UniReversedPreserving: ", uniReversedPreserving(str)


*        Repeat a string           - 19/04/2020
REPEATS  CSECT
         USING  REPEATS,R13        base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         SAVE   (14,12)            save previous context
         ST     R13,4(R15)         link backward
         ST     R15,8(R13)         link forward
         LR     R13,R15            set addressability
         XPRNT  C24,24             print c24
         LA     R1,PARMLST         pg=repeat(cx,ii) - repeat('abc ',6)
         BAL    R14,REPEAT         call repeat
         XPRNT  PG,L'PG            print pg
         L      R13,4(0,R13)       restore previous savearea pointer
         RETURN (14,12),RC=0       restore registers from calling save
REPEAT   CNOP   0,4                procedure repeat(b,a,i)
         STM    R2,R8,REPEATSA     save registers
         L      R2,0(R1)           @b=%r1
         L      R3,4(R1)           @a=%(r1+4)
         L      R4,8(R1)           @i=%(r1+8)
         LR     R5,R3              length(a) before a
         SH     R5,=H'2'           @lengh(a)
         LH     R6,0(R5)           l=length(a)
         LR     R7,R6              l
         BCTR   R7,0               l-1
         L      R8,0(R4)           i=%r4
         LTR    R8,R8              if i<=0
         BNP    RET                then return
LOOP     EX     R7,MVCX            move a to b len R6
         AR     R2,R6              @b+=l
         BCT    R8,LOOP            loop i times
RET      LM     R2,R8,REPEATSA     restore registers
         BR     R14                return
PARMLST  DC     A(PG,CX,II)        parmlist
REPEATSA DS     7F                 local savearea
MVCX     MVC    0(0,R2),0(R3)      move @ R3 to @ R2
C24      DC     6C'xyz '           constant repeat - repeat('xyz ',6)
LCX      DC     AL2(L'CX)          lengh(cc)
CX       DC     CL4'abc '          cx
II       DC     F'6'               ii
PG       DC     CL80' '            pg
         REGEQU
         END    REPEATS


gosub repeat ha 5
echo %@repeat[*,5]
quit

:Repeat [String Times]
    do %Times%
        echos %String%
    enddo
    echo.
return


CHROUT equ $FFD2    ;KERNAL call, prints the accumulator to the screen as an ascii value.

	org $0801

	db $0E,$08,$0A,$00,$9E,$20,$28,$32,$30,$36,$34,$29,$00,$00,$00

	lda #>TestStr
	sta $11

	lda #<TestStr
	sta $10

	ldx #5				;number of times to repeat

loop:
	jsr PrintString
	dex
	bne loop

	RTS					;RETURN TO BASIC

PrintString:
	ldy #0
loop_PrintString:
	lda ($10),y			;this doesn't actually increment the pointer itself, so we don't need to back it up.
	beq donePrinting
	jsr CHROUT
	iny
	jmp loop_PrintString
donePrinting:
	rts

TestStr:
	db "HA",0


10 STRING$="THIS TEXT IS REVERSED."
20 REVERSED$=""
30 FOR I=1 TO LEN(STRING$)
40 REVERSED$=MID$(STRING$,I,1)+REVERSED$
50 NEXT
60 PRINT REVERSED$


MODULE reverse;

   IMPORT Out, Strings;

   VAR s: ARRAY 12 + 1 OF CHAR;

   PROCEDURE Swap(VAR c, d: CHAR);
      VAR oldC: CHAR;
   BEGIN
      oldC := c; c := d; d := oldC
   END Swap;

   PROCEDURE Reverse(VAR s: ARRAY OF CHAR);
      VAR len, i: INTEGER;
   BEGIN
      len := Strings.Length(s);
      FOR i := 0 TO len DIV 2 DO
         Swap(s[i], s[len - 1 - i])
      END
   END Reverse;

BEGIN
   s := "hello, world";
   Reverse(s);
   Out.String(s);
   Out.Ln
END reverse.


MOVE.W #5-1,D1
RepString:
LEA A3, MyString
MOVE.L A3,-(SP) ;PUSH A3
JSR PrintString ;unimplemented hardware-dependent printing routine, assumed to not clobber D1
MOVE.L (SP)+,A3 ;POP A3
DBRA D1,RepString
RTS             ;return to basic or whatever

MyString:
DC.B "ha",0
even


report z_repeat_string.

write repeat( val = `ha`  occ = 5 ).


#import <Foundation/Foundation.h>

@interface NSString (Extended)
-(NSString *)reverseString;
@end

@implementation NSString (Extended)
-(NSString *) reverseString
{
    NSUInteger len = [self length];
    NSMutableString *rtr=[NSMutableString stringWithCapacity:len];
    //        unichar buf[1];

    while (len > (NSUInteger)0) {
        unichar uch = [self characterAtIndex:--len];
        [rtr appendString:[NSString stringWithCharacters:&uch length:1]];
    }
    return rtr;
}
@end


Proc Main()
 byte REPEAT

 REPEAT=5
  Do
   Print("ha")
   REPEAT==-1
   Until REPEAT=0
  Do

Return


function repeatString(string:String, numTimes:uint):String
{
	var output:String = "";
	for(var i:uint = 0; i < numTimes; i++)
		output += string;
	return output;
}


with Ada.Strings.Fixed;  use Ada.Strings.Fixed;
with Ada.Text_IO;        use Ada.Text_IO;

procedure String_Multiplication is
begin
   Put_Line (5 * "ha");
end String_Multiplication;


let string_rev s =
  let len = String.length s in
  String.init len (fun i -> s.[len - 1 - i])

let () =
  print_endline (string_rev "Hello world!")


#!/usr/bin/hopper
#include <hopper.h>

main:
  {"ha"}replyby(5),    println
  {"ha",5}replicate,   println
{0}return


(define (rev s)
   (runes->string (reverse (string->runes s))))

; testing:
(print (rev "Hello, λ!"))
; ==> !λ ,olleH


main: func {
  "asdf" reverse() println() // prints "fdsa"
}


set str to "ha"
set final_string to ""
repeat 5 times
    set final_string to final_string & str
end repeat


FOR I = 1 TO 5 : S$ = S$ + "HA" : NEXT

? "X" SPC(20) "X"


FUNCTION reverseString RETURNS CHARACTER (
   INPUT i_c AS CHARACTER
):

   DEFINE VARIABLE cresult AS CHARACTER   NO-UNDO.
   DEFINE VARIABLE ii      AS INTEGER     NO-UNDO.

   DO ii = LENGTH( i_c ) TO 1 BY -1:
      cresult = cresult + SUBSTRING( i_c, ii, 1 ).
   END.
   RETURN cresult.

END FUNCTION.

MESSAGE reverseString( "asdf" ) VIEW-AS ALERT-BOX.


'8 BIT CHARACTERS

string s="qwertyuiop"
sys a,b,i,j,le=len s
'
for i=1 to le
  j=le-i+1
  if j<=i then exit for
  a=asc s,i
  b=asc s,j
  mid s,j,chr a
  mid s,i,chr b
next
'

print s

'16 BIT CHARACTERS

wstring s="qwertyuiop"
sys a,b,i,j,le=len s
'
for i=1 to le
  j=le-i+1
  if j<=i then exit for
  a=unic s,i
  b=unic s,j
  mid s,j,wchr a
  mid s,i,wchr b
next
'
print s


string s="qwertyuiop"
sys p=strptr s, le=len s
mov esi,p
mov edi,esi
add edi,le
dec edi
(
 cmp esi,edi
 jge exit
 mov al,[esi]
 mov ah,[edi]
 mov [esi],ah
 mov [edi],al
 inc esi
 dec edi
 repeat
)

print s


MsgBox % Repeat("ha",5)

Repeat(String,Times)
{
  Loop, %Times%
    Output .= String
  Return Output
}


#include <String.au3>

ConsoleWrite(_StringRepeat("ha", 5) & @CRLF)


{System.showInfo {Reverse "!dlroW olleH"}}


{ the result array must be at least as large as the original array }
procedure reverse(s: array[min .. max: integer] of char, var result: array[min1 .. max1: integer] of char);
 var
  i, len: integer;
 begin
  len := max-min+1;
  for i := 0 to len-1 do
   result[min1 + len-1 - i] := s[min + i]
 end;


function repeat( str, n,    rep, i )
{
    for( ; i<n; i++ )
        rep = rep str
    return rep
}

BEGIN {
    print repeat( "ha", 5 )
}


main: { "ha" 5 print_repeat }

print_repeat!: { <- { dup << } -> times }


DOTIMES 5
    s$ = s$ & "ha"
DONE
PRINT s$


<# 显示 指定 变量 反转顺序 字串>集装箱|猫坐在垫子</#>


use utf8;
binmode STDOUT, ":utf8";

# to reverse characters (code points):
print reverse('visor'), "\n";

# to reverse graphemes:
print join("", reverse "José" =~ /\X/g), "\n";

$string = 'ℵΑΩ 駱駝道 🤔 🇸🇧 🇺🇸 🇬🇧 👨👩👧👦🆗🗺';
print join("", reverse $string =~ /\X/g), "\n";


function StringRepeat$ (s$, n)
	cad$ = ""
	for i = 1 to n
		cad$ += s$
	next i
	return cad$
end function

print StringRepeat$("rosetta", 1)
print StringRepeat$("ha", 5)
print StringRepeat$("*", 5)
end


@echo off
if "%2" equ "" goto fail
setlocal enabledelayedexpansion
set char=%1
set num=%2
for /l %%i in (1,1,%num%) do set res=!res!%char%
echo %res%
:fail


          p    <
      p0~1<}~< [email protected]<
[email protected]~>[email protected]'d;


Repeat ← ×⟜≠ ⥊ ⊢

•Show 5 Repeat "Hello"


(repeat=
  string N rep
.   !arg:(?string.?N)
  & !string:?rep
  &   whl
    ' (!N+-1:>0:?N&!string !rep:?rep)
  & str$!rep
);


+++++ +++++	init first as 10 counter
[-> +++++ +++++<] we add 10 to second each loopround

		Now we want to loop 5 times to follow std
+++++
[-> ++++ . ----- -- . +++<] print h and a each loop

and a newline because I'm kind and it looks good
+++++ +++++ +++ . --- .


To run:
Start up.
Put "asdf" into a string.
Reverse the string.
Shut down.


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


blsq ) 'h5?*
"hhhhh"
blsq ) "ha"5.*\[
"hahahahaha"


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char * string_repeat( int n, const char * s ) {
  size_t slen = strlen(s);
  char * dest = malloc(n*slen+1);

  int i; char * p;
  for ( i=0, p = dest; i < n; ++i, p += slen ) {
    memcpy(p, s, slen);
  }
  *p = '\0';
  return dest;
}

int main() {
  char * result = string_repeat(5, "ha");
  puts(result);
  free(result);
  return 0;
}


string s = "".PadLeft(5, 'X').Replace("X", "ha");


/reverse{
/str exch def
/temp str 0 get def
/i 0 def
str length 2 idiv{
/temp str i get def
str i str str length i sub 1 sub get put
str str length i sub 1 sub temp put
/i i 1 add def
}repeat
str pstack
}def


#DIM ALL
#COMPILER PBCC 6

FUNCTION PBMAIN () AS LONG
CON.PRINT STRREVERSE$("PowerBASIC")
END FUNCTION


#include <string>
#include <iostream>

std::string repeat( const std::string &word, int times ) {
   std::string result ;
   result.reserve(times*word.length()); // avoid repeated reallocation
   for ( int a = 0 ; a < times ; a++ )
      result += word ;
   return result ;
}

int main( ) {
   std::cout << repeat( "Ha" , 5 ) << std::endl ;
   return 0 ;
}


shared void repeatAString() {
	print("ha".repeat(5));
}


F repeat(f, n)
   L 1..n
      f()

F procedure()
   print(‘Example’)

repeat(procedure, 3)


IDENTIFICATION DIVISION.
PROGRAM-ID. REPEAT-PROGRAM.
DATA DIVISION.
WORKING-STORAGE SECTION.
77  HAHA         PIC A(10).
PROCEDURE DIVISION.
    MOVE ALL 'ha' TO HAHA.
    DISPLAY HAHA.
    STOP RUN.


<cfset word = 'ha'>
<Cfset n = 5>
<Cfoutput>
<Cfloop from="1" to="#n#" index="i">#word#</Cfloop>
</Cfoutput>


  [ dup nest? if
      [ [] swap witheach
          [ nested
            swap join ] ] ]     is reverse      (       x --> x       )


revstring <- function(stringtorev) {
   return(
      paste(
           strsplit(stringtorev,"")[[1]][nchar(stringtorev):1]
           ,collapse="")
           )
}


macro RepeatProc,addr,count ;VASM macro syntax
; input:
; addr = the label of the routine you wish to call repeatedly
; count = how many times you want to DO the procedure. 1 = once, 2 = twice, 3 = three times, etc. Enter "0" for 256 times.
lda #<\addr
sta z_L ;a label for a zero-page memory address
lda #>\addr
sta z_H ;a label for the zero-page memory address immediately after z_L
lda \count
jsr doRepeatProc
endm

doRepeatProc:
sta z_C   ;another zero-page memory location
loop_RepeatProc:
jsr Trampoline_RepeatProc
dec z_C
lda z_C
bne loop_RepeatProc
rts

Trampoline_RepeatProc:
db $6c,z_L,$00
;when executed, becomes an indirect JMP to the address stored at z_L and z_H. Some assemblers will let you type
;JMP (z_L) and it will automatically replace it with the above during the assembly process.
;This causes an indirect JMP to the routine. Its RTS will return execution to just after the "JSR Trampoline_RepeatProc"
;and flow into the loop overhead.


	lea foo,a5            ;function to execute
	move.w #4-1,d7        ;times to repeat
	jsr Repeater

	jmp *                 ;halt the CPU, we're done

repeater:
	jsr repeaterhelper    ;this also need to be a call, so that the RTS of the desired procedure
                              ;returns us to the loop rather than the line after "jsr Repeater".
	DBRA D7,repeater
	rts

repeaterhelper:
	jmp (a5)       ;keep in mind, this is NOT a dereference, it simply sets the program counter equal to A5.
                       ;A bit misleading if you ask me.
foo:
	MOVE.B #'!',D0
	JSR PrintChar
	rts