Reputation: 2781
I was asked this question on how to reverse a string without allocating memory. Any takers?
Upvotes: 0
Views: 894
Reputation: 2781
void reverseStringBetter(char* str)
{
int i, j;
i=j=0;
j=strlen(str)1;
for (i=0; i<j; i++, j-)
{
str[i] ^= str[j] ;
str[j] ^= str[i] ;
str[i] ^= str[j] ;
}
}
Upvotes: 1
Reputation: 28240
It is not possible with NSString
since they are immutable and the only way is to create a new string.
Though this might not be what you are looking for, you can convert the NSString
to a normal c-string, and edit that in-place. You are still allocating memory, but you'll at least get half of what you want by being able to modify the string in place.
I'm not sure what your use case is for not wanting to allocate memory, or if this is simply a hypothetical.
Upvotes: 0
Reputation: 385600
You cannot reverse an NSString
, with or without allocating memory, because an NSString
is immutable.
You cannot reverse an NSMutableString
in place without allocating memory, because the only methods that NSMutableString
provides to replace its contents require the new characters to be specified in an NSString
, which you would have to allocate.
CFMutableString
has the same “problem”.
Upvotes: 4