Lesson 26 of 28

String Reversal

Reversing a String

Reversing a string in-place is a classic exercise that combines string iteration, memory access, and the two-pointer technique.

The Two-Pointer Technique

Use two indices: one starting at the beginning (left) and one at the end (right). Swap the characters at these positions, then move both pointers inward:

"abcde"
 ^   ^    swap 'a' and 'e' → "ebcda"
  ^ ^     swap 'b' and 'd' → "edcba"
  ^^       left >= right, done!

Step 1: Find the Length

First, iterate to find the string length (position of the null terminator):

LDR X0, =str
MOV X1, #0
len_loop:
    LDRB W2, [X0, X1]
    CBZ W2, len_done
    ADD X1, X1, #1
    B len_loop
len_done:
// X1 = length

Step 2: Swap with Two Pointers

MOV X2, #0           // left = 0
SUB X3, X1, #1       // right = length - 1

rev_loop:
    CMP X2, X3
    B.GE rev_done
    LDRB W4, [X0, X2]   // tmp = str[left]
    LDRB W5, [X0, X3]   // load str[right]
    STRB W5, [X0, X2]   // str[left] = str[right]
    STRB W4, [X0, X3]   // str[right] = tmp
    ADD X2, X2, #1
    SUB X3, X3, #1
    B rev_loop
rev_done:

Your Task

Reverse the string "abcde" in-place and print the result (edcba) followed by a newline.

ARM64 runtime loading...
Loading...
Click "Run" to execute your code.