Lesson 27 of 28
String Comparison
Comparing Strings
Comparing two strings byte-by-byte is one of the most common operations in programming. In assembly, you implement it manually -- there is no built-in strcmp.
The Algorithm
Compare corresponding bytes from two strings until:
- You find two bytes that differ → strings are not equal
- Both bytes are null terminators → strings are equal
LDR X0, =str1
LDR X1, =str2
cmp_loop:
LDRB W2, [X0], #1 // Load byte from str1, advance
LDRB W3, [X1], #1 // Load byte from str2, advance
CMP W2, W3
B.NE not_equal // Bytes differ
CBZ W2, equal // Both are null → match!
B cmp_loop
equal:
// Strings are equal
not_equal:
// Strings are different
Post-Increment for Iteration
Notice [X0], #1 -- this is the post-index addressing mode. It loads the byte at [X0], then adds 1 to X0. Perfect for walking through strings.
Why Check Both Conditions?
CMP W2, W3/B.NEcatches mismatched bytes at any positionCBZ W2catches the end of both strings (if we reach here, W2 == W3, so if W2 is 0 then both strings ended at the same point)
Your Task
Compare the strings "hello" and "hello". If they are equal, print EQ followed by a newline. If not, print NE followed by a newline.
ARM64 runtime loading...
Loading...
Click "Run" to execute your code.