开发者

Test if NSString ends with whitespace or newline character?

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜