Raku Books / Using Raku / Strings / Modifying string data

5. Reverse a string

Print a string in the reversed order from right to left.

Strings, or the objects of the Str class, have the flip method, which does the work:

my $string = 'Hello, World!';
say $string.flip;

This code prints the desired result:

!dlroW ,olleH

The flip routine may be called both as a method on a string and as a standalone function:

say flip 'Abcdef'; # fedcbA
say 'Word'.flip;   # droW

Don’t forget that say can also be called as a method:

'Magic'.flip.say; # cigaM

There is also the reverse routine, but it cannot be applied directly to strings. It accepts lists, so a string first has to be converted to the list of characters, then reversed, and later joined again to a string.

Here is the code that works according to this description.

my $string = 'Hello, World!';
my $reversed = $string.split('').reverse().join('');
say $reversed; # !dlroW ,olleH

Course navigation

Modifying string data   |   6. Removing blanks from a string