ma11hew28
ma11hew28

Reputation: 126367

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?

Upvotes: 12

Views: 5443

Answers (3)

user94896
user94896

Reputation:

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]) {
  // ...
}

Upvotes: 21

ma11hew28
ma11hew28

Reputation: 126367

@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

Upvotes: 2

Robin
Robin

Reputation: 10011

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].

Upvotes: 5

Related Questions