On 24 Dec 2008, at 5:00 am, Alex.Wang wrote:
Hi everyone.
I came across a confusing issue, please see the following code:
NSLog(@"Trick here: %@", [[NSString stringWithString:@"There are
blanks"]
stringByTrimmingCharactersInSet:
[NSCharacterSet
whitespaceAndNewlineCharacterSet]]);
We may expect to see "Trick here: Thereareblanks" output from the
console.
However, I got "Trick here: There are blanks" instead. I dont
know why
the stringByTrimmingCharactersInSet method doesn't work.
Can anyone here give me an explanation or tell me how to solve it?
Thank you very much for your help. Good luck.
Yeah, I misinterpreted this method also. It only removes characters
from the ends. Not sure when that would be useful, but anyway. I wrote
a couple of category methods to handle this:
- (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;
}
- (NSString *) stringByRemovingCharactersInSet:(NSCharacterSet*)
charSet
{
return [self stringByRemovingCharactersInSet:charSet options:0];
}
hth, Graham
_______________________________________________
Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)
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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to arch...@mail-archive.com