Re: stringByTrimmingCharactersInSet
Re: stringByTrimmingCharactersInSet
- Subject: Re: stringByTrimmingCharactersInSet
- From: Graham Cox <email@hidden>
- Date: Thu, 7 May 2009 13:27:51 +1000
On 07/05/2009, at 11:16 AM, Simon Raisin wrote:
NSString *s = [@"1,660.0" stringByTrimmingCharactersInSet:
[NSCharacterSet
characterSetWithCharactersInString:@","]];
For some reason s is always "1,660.0".
Shouldn't the comma be removed?
No, that method only trims characters from the ends of the string, not
from within it. While this doesn't sound all that useful it can be
handy for tidying up fixed-length records from old database formats
(that's so far the only use I've found for it!)
For 10.5 and later, you can do:
[myString stringByReplacingOccurrencesOfString:@"," withString:@""];
For earlier OS, you'll need to roll your own, such as this NSString
category method:
- (NSString *) stringByRemovingCharactersInSet:(NSCharacterSet*)
charSet options:(unsigned) mask
{
NSRange range;
NSMutableString* newString = [NSMutableString string];
unsigned len = [self length];
mask &= ~NSBackwardsSearch;
range = NSMakeRange (0, len);
while (range.length)
{
NSRange substringRange;
unsigned pos = range.location;
range = [self rangeOfCharacterFromSet:charSet options:mask
range:range];
if (range.location == NSNotFound)
range = NSMakeRange (len, 0);
substringRange = NSMakeRange (pos, range.location - pos);
[newString appendString:[self substringWithRange:substringRange]];
range.location += range.length;
range.length = len - range.location;
}
return newString;
}
--Graham
_______________________________________________
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