Re: Adding spaces to an NSString
Re: Adding spaces to an NSString
- Subject: Re: Adding spaces to an NSString
- From: "stephen joseph butler" <email@hidden>
- Date: Tue, 18 Mar 2008 23:10:06 -0500
On Tue, Mar 18, 2008 at 7:40 PM, J. Todd Slack <
email@hidden> wrote:
> Hello All,
>
> I am a little stumped today, not sure why, but how would I add a space
> after
> every character in an NSString and produce a new NSString from it.
>
> So I have something like: (ignore the quotes, I just did it for
> containment
> sake..)
>
> ³/Users/slack/Music²
>
> And I want it to be:
>
> ³/ U s e r s / s l a c k / M u s i c ³
>
> Would anyone have any thoughts?
Yes; there's not a good, easy way to do this. One implementation that at
first seems correct is this:
from = [NSMutableString string];
for (int i = 0; i < [to length]; ++i)
[from appendFormat:@"%C ", [from characterAtIndex:i]];
That is, until you realize that unichar is 16 bit, and some "characters" are
encoded as two unichar's. Opps! A better implementation, relying on the fact
that NSString is UTF16 (I don't think endianess would matter here), would do
this:
from = [NSMutableString string];
for (int i = 0; i < [to length]; ++i) {
unichar c = [from characterAtIndex:i];
if ((c >= 0xD800) && (c <= 0xDBFF))
[from appendFormat:@"%C", c];
else
[from appendFormat:@"%C ", c];
}
But that's a little hacky. Perhaps the best way, the way I would probably do
it, is to encode the string as UTF-32 in one buffer, insert the spaces using
another, and then decode back to an NSString. Then you aren't relying on the
internal representation and size of unichar, although I seriously doubt
Apple will change it any time soon.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden