How do I test if the last character of开发者_运维问答 an NSString is a whitespace or newline character.
I could do [[NSCharacter whitespaceAndNewlineCharacterSet] characterIsMember:lastChar]. But, how do I get the last character of an NSString?
Or, should I just use - [NSString rangeOfCharacterFromSet:options:] with a reverse search?
You're on the right track. The following shows how you can retrieve the last character in a string; you can then check if it's a member of the whitespaceAndNewlineCharacterSet as you suggested.
unichar last = [myString characterAtIndex:[myString length] - 1];
if ([[NSCharacterSet whitespaceAndNewlineCharacterSet] characterIsMember:last]) {
// ...
}
Maybe you can use length on an NSString object to get its length and then use:
- (unichar)characterAtIndex:(NSUInteger)index
with index as length - 1. Now you have the last character which can be compared with [NSCharacter whitespaceAndNewlineCharacterSet].
@implementation NSString (Additions)
- (BOOL)endsInWhitespaceOrNewlineCharacter {
NSUInteger stringLength = [self length];
if (stringLength == 0) {
return NO;
}
unichar lastChar = [self characterAtIndex:stringLength-1];
return [[NSCharacterSet whitespaceAndNewlineCharacterSet] characterIsMember:lastChar];
}
@end
加载中,请稍侯......
精彩评论