How to check the last char of an NSString
I want to ask a question about the NSString * in objective C. Can I check the last char of a NSString * object?
Example:
NSString* data = @"abcde,";
if(data is end with ',') // I don't know this part
// do sth
NSString *data = @"abcde,";
if([data hasSuffix:@","]) // This returns true in this example
// do something
The NSString Programming Guide recommends:
If you simply want to determine whether a string contains a given pattern, you can use a predicate:
So, in your example:
NSString *data = @"abcde,";
// Create the predicate
NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"SELF endswith %@", @","];
// Run the predicate
// match == YES if the predicate is successful
BOOL match = [myPredicate evaluateWithObject:data];
// Do what you want
if (match) {
// do something
}
A bit long winded to write? Maybe, but if you do this in more than one place it can be easily refactored into a helper method.
Here's a link to the NSPredicate docs.
Edit
I've done some profiling and it is overkill in this simple case (see my comment below). I'll leave the answer up here anyway just as an example of using predicates for this sort of thing.