Code patternsDataReverse a string

Reverse a string

Prints a text back to front.

Watch it run

The form “The whole input” works on 10 cells; the named ones are “zero”, “letter” and “end”. Press Play, drag the step slider forwards and back, or edit the input:

The figure needs JavaScript. The program below is the result for the example values.

After the reading loop (see read a line into memory), the pointer stands just past the last letter. One step left is the last letter.

[.<] prints the cell and steps left, until it meets the zero cell before the string. Reversing costs nothing extra: it is the direction the pointer has to walk anyway.

The code

This is the program the figure ran. It is brainfuck as it stands: copy it, or open it in the playground, where you can change it:

>,[>,]<[.<]
Open in the playground11 characters

What it needs

Common mistakes
  • Text in more than one byte per letter (é, 你): the bytes of each letter come out in the wrong order. The tape holds bytes, not letters.

What it costs

A plain step is one command. An optimised step is one step of an interpreter that folds runs of the same command and flat loops. Choose the values and watch the two bars; What costs what explains how cost is counted:

The figure needs JavaScript. The table below has the measured steps.

Cost as a formula, and measured
Table 1. The cost as a function of the values. Exact formulas are checked on every case they run.
FormPlain stepsOptimised steps
The whole input5 + 6 per letter3 + 4 per letter
One line15 + 26 per letter4 + 6 per letter
Clearing up behind itgrows with the letter codes3 + 5 per letter
Table 2. Measured when this page was written.
FormValuesBitsCharactersPlain stepsOptimised steps
The whole inputthe input = ""81153
The whole inputthe input = "stressed"8115335
One linethe line = "stressed"84122352
Clearing up behind itthe input = "stressed"8141,81543

Other forms

One line

Stops at the newline and does not print it.

>,----------[++++++++++>,----------]<[.<]
Open in the playground41 characters
Run this form step by step

The form “One line” works on 10 cells; the named ones are “zero”, “letter” and “end”. Press Play, drag the step slider forwards and back, or edit the line:

The figure needs JavaScript. The program below is the result for the example values.

Clearing up behind it

Each letter is erased after it is printed, so the tape ends empty.

>,[>,]<[.[-]<]
Open in the playground14 characters
Run this form step by step

The form “Clearing up behind it” works on 10 cells; the named ones are “zero”, “letter” and “end”. Press Play, drag the step slider forwards and back, or edit the input:

The figure needs JavaScript. The program below is the result for the example values.

Where it is used

Sources

Every program on this page was run on many inputs, in plain and in optimised mode, and compared with JavaScript. The explanations are written for this page.