Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if NSString end with string

I would like to check if my NSString end with @2x.png (case insensitive). How can I do that?

I have this code now, but it seems to ignore the @2x part.

    NSString *fileName = [_sourcePath lastPathComponent];
    [fileName stringByReplacingOccurrencesOfString:@"@2x" withString:@""];
    [fileName stringByReplacingOccurrencesOfString:@"@2X" withString:@""];
    NSLog(@"Filename: %@", fileName);

2012-01-01 21:00:55.600 NewApp[23930:707] Filename: [email protected]

like image 602
Paul Peelen Avatar asked Jun 03 '26 20:06

Paul Peelen


1 Answers

Try something like this:

NSRange range = [fileName rangeOfString:@"@2x.png" options:NSCaseInsensitiveSearch];

if ( range.location != NSNotFound &&
     range.location + range.length == [fileName length] )
{
    NSLog(@"%@ ends with @2x.png",fileName);
}

ps. Note that you should assure that fileName is not nil before calling rangeOfString, since you're calling a method which does not return id. Calling a method on nil returns nil, which is not compatible with the NSRange type, and will lead to unexpected results.

like image 61
mvds Avatar answered Jun 07 '26 22:06

mvds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!