ios - Reverse NSString recursively in category -
this question has answer here:
- reverse nsstring text 19 answers
i made category reversing nsstring
in recursive way. i'm getting correct answer. i'm not sure if okay memory management. don't know memory management in objective-c.
any other efficient way highly admirable.
-(nsstring *)reversestring{ if ([self length]<2) { return self; } else { return [[[self substringfromindex:1] reversestring] stringbyappendingstring:[self substringtoindex:1]]; } }
however, question similar reverse nsstring text not duplicate because here i'm implementing recursion. , asked memory consumption not code example.
using recursion reverse string interesting thought exercise, goning slow , dreadful wasteful of memory. need create 2n temporary strings. (where n number of characters in string) n of strings 1 character long, , other n strings 1, 2, 3, 4, 5, etc. characters, n-1.
(memory allocation slow.)
plus create n stack frames. rmaddy says in comment, you'll cause stack overflow long strings.
if doing learn recursion, fine. otherwise, toss approach , write code loops through array backwards, appending each character mutable string.