How to check last char NSString

I want to ask a question about NSString * in object C. Can I check the last char of an NSString * object?

Example:

NSString* data = @"abcde,"; if(data is end with ',') // I don't know this part // do sth 

Thank you very much.

+57
objective-c cocoa nsstring
Jul 14 '10 at 9:48 on
source share
3 answers
 NSString *data = @"abcde,"; if([data hasSuffix:@","]) // This returns true in this example // do something 
+161
Jul 14 '10 at 10:05
source share

NSString Programming Guide recommends:

If you just want to determine if a string contains a given pattern, you can use the 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 little longer to write? Perhaps, but if you do this in more than one place, it can be easily rebuilt into a helper method.

Here is a link to NSPredicate docs .

Edit

I did some profiling, and this is unnecessary in this simple case (see my comment below). In any case, I will leave the answer here as an example of using predicates for this kind of thing.

+5
Jul 14 2018-10-14T00:
source share

If you are concerned about performance and you want to check for a single character, using the -characterAtIndex: method might be faster. -hasSuffix: takes a string, so potentially more work needs to be done than just checking a single character (although the difference may be trivial).

You can also use categories to add a method to NSString as follows:

 @interface NSString(StringUtilities) - (BOOL) endsWithCharacter: (unichar) c; @end @implementation NSString(StringUtilities) - (BOOL) endsWithCharacter: (unichar) c { NSUInteger length = [self length]; return (length > 0) && ([self characterAtIndex: length - 1] == c); } @end // test it... NSString *data = @"abcd,"; if ([data endsWithCharacter: L',']) { } 

Of course you should comment, of course. Keep in mind that by adding endWithCharacter to the method, we added overhead to it that will distort the profiling results if you do not do the same when profiling alternatives.

All of this is probably a premature optimization for most cases - but, of course, if you do this test thousands of times per second, it can make a difference (in this case, you probably want to use the code directly in a loop, because the message passing inside is hard inner loop is not a great plan).

+4
Jul 16 2018-10-10T00:
source share



All Articles