I have a NSString object which is assigned this ("http://vspimages.vsp.virginia.gov/images/024937-02.jpg"). Can anybody tell me how to check whether the string ends with ".jpg"?
Asked
Active
Viewed 2.7k times
3 Answers
141
if ([[yourString pathExtension] isEqualToString:@"jpg"]){
//.jpg
}
or
if ([yourString hasSuffix:@".jpg"]){
//.jpg
}

Vladimir
- 170,431
- 36
- 387
- 313
-
2i have already tried this [yourString hasSuffix:@".jpg"] this but its not working... – RAMAN RANA Mar 09 '11 at 10:24
-
Have you tried to log your string to check if it has expected value? also I think, 1st approach is more appropriate in your case – Vladimir Mar 09 '11 at 10:26
-
3You should really use a case insensitive compare – nylund Mar 15 '13 at 12:49
6
appending to vladimir's answer, you may wish to make a case insensitive comparison. Here's how I did it:
if( [[yourString pathExtension] caseInsensitiveCompare:@"jpg"] == NSOrderedSame ) {
// strings are equal but may not be same case
}

StenaviN
- 3,687
- 24
- 34

ThinkBonobo
- 15,487
- 9
- 65
- 80
2
NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.png' AND self BEGINSWITH[c] %@",@"img_"];
if([fltr evaluateWithObject:strPath])
{
// string matched....
}

Atif Mahmood
- 8,882
- 2
- 41
- 44