Reputation: 126367
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
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
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
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