Re: attributedStringByTrimmingCharactersInSet: method?
Re: attributedStringByTrimmingCharactersInSet: method?
- Subject: Re: attributedStringByTrimmingCharactersInSet: method?
- From: Justin Anderson <email@hidden>
- Date: Sun, 23 Jul 2006 10:44:30 -0400
Here's a shorter version, though it may need more checking than just
the one if statement.
- (NSAttributedString *)attributedStringByTrimmingCharactersInSet:
(NSCharacterSet *)set
{
NSRange frontRange, endRange, finalRange;
NSCharacterSet invertedSet = [set invertedSet];
// Find the range of the first character you want to keep
frontRange = [[newStr string] rangeOfCharacterFromSet:set];
// Find the range of the last character you want to keep
endRange = [[newStr string] rangeOfCharacterFromSet:set
options:NSBackwardsSearch];
// might need more range checks than this
if (frontRange.location == NSNotFound)
{
return nil;
}
finalRange = NSMakeRange(frontRange.location, NSMaxRange(endRange) -
frontRange.location);
return [self attributedSubstringFromRange:finalRange];
}
Justin Anderson
On Jul 23, 2006, at 10:16 AM, Keith Blount wrote:
Thanks for your reply - much appreciated.
I tried your idea, but the trouble with using the
string methods directly, such as in your example, is
that all of the formatting and attributes of the
attributed string get stripped, which is obviously
counter-productive.
For now I have created my own NSAttributedString
category that provides the methods I need as follows:
- (NSAttributedString
*)attributedStringByTrimmingCharactersInSet:(NSCharacterSet
*)set
{
NSMutableAttributedString *newStr = [[self
mutableCopy] autorelease];
NSRange range;
// First clear any characters from the set from the
beginning of the string
range = [[newStr string]
rangeOfCharacterFromSet:set];
while (range.length != 0 && range.location == 0)
{
[newStr replaceCharactersInRange:range
withString:@""];
range = [[newStr string]
rangeOfCharacterFromSet:set];
}
// Then clear them from the end
range = [[newStr string] rangeOfCharacterFromSet:set
options:NSBackwardsSearch];
while (range.length != 0 && NSMaxRange(range) ==
[newStr length])
{
[newStr replaceCharactersInRange:range
withString:@""];
range = [[newStr string] rangeOfCharacterFromSet:set
options:NSBackwardsSearch];
}
return [[[NSAttributedString alloc]
initWithAttributedString:newStr] autorelease];
}
- (NSAttributedString
*)attributedStringByTrimmingWhitespace
{
return [self
attributedStringByTrimmingCharactersInSet:[NSCharacterSet
whitespaceAndNewlineCharacterSet]];
}
This seems to work fine, though if anyone thinks this
should be done in a better or more graceful way, I
would be grateful to hear about it.
Thanks again and all the best,
Keith
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden