Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 43 / 68

Reversing a string and testing for a palindrome

This lesson covers reversing a string and testing for a palindrome in Objective-C, with the aim of understanding the basics of string handling.

A string that reads the same forwards and backwards is a palindrome. Objective-C has no dedicated method for reversing a string, so the usual approach is to take the characters one at a time and assemble them in reverse.

In the sample code, a reverseString() function loops from str.length - 1 down to 0, appending one character at a time with [reversed appendFormat:@"%C", ...]. Note the %C specifier for a single character.

A common early stumble is needing an NSMutableString. NSString is immutable, so building up characters one at a time calls for the mutable version.

Reversal and palindrome checks rarely come up directly in practice, but they are a classic subject for practising how strings are handled.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)