在字符串中搜索子字符串数组

时间:2022-09-13 11:33:34

I want to check whether a string contains any of the substrings that I place in an array. Basically, I want to search the extensions of a file, and if the file is an "image", i want certain code to execute. The only way I can think of categorizing the file as an "Image" without downloading the file is through the substring in a string method. This is my code so far:

我想检查一个字符串是否包含我放在数组中的任何子字符串。基本上,我想搜索文件的扩展名,如果文件是“图像”,我想要执行某些代码。我可以想到在不下载文件的情况下将文件分类为“图像”的唯一方法是通过字符串方法中的子字符串。到目前为止这是我的代码:

NSString *last5Chars = [folderName substringFromIndex: [folderName length] - 5];

         NSRange textRangepdf;
         textRangepdf =[last5Chars rangeOfString:@"pdf"];

         if(textRangepdf.location != NSNotFound)
          {
         [self.itemType addObject:@"PDF.png"];
          }

Is it possible to do this where I can check if last5Chars contains @"jpg" or @"gif" of @"png" etc...?? Thanks for helping!

是否可以这样做,我可以检查last5Chars是否包含@“jpg”或@“png”的@“gif”等等?谢谢你的帮助!

3 个解决方案

#1


1  

NSString *fileName;
NSArray *imgExtArray; // put your file extensions in here
BOOL isImage = [imgExtArray containsObject:[fileName pathExtension]];

#2


0  

[folderName hasSuffix:@".jpg"] || [folderName hasSuffix:@".gif"]

obviously you can put it into a loop, if you have a whole arrayful.

显然你可以把它放到一个循环中,如果你有一个完整的阵列。

#3


0  

Rather than mess about with ranges and suffixes, NSString has a method that treats an NSString as a path and returns an extension, it's called pathExtension.

NSString有一个方法将NSString视为路径并返回一个扩展名,而不是乱七八糟的范围和后缀,它被称为pathExtension。

Have a look in the NSString Documentation

查看NSString文档

Once you get the extension you can check it against whatever strings you want.

获得扩展后,您可以根据所需的字符串进行检查。

#1


1  

NSString *fileName;
NSArray *imgExtArray; // put your file extensions in here
BOOL isImage = [imgExtArray containsObject:[fileName pathExtension]];

#2


0  

[folderName hasSuffix:@".jpg"] || [folderName hasSuffix:@".gif"]

obviously you can put it into a loop, if you have a whole arrayful.

显然你可以把它放到一个循环中,如果你有一个完整的阵列。

#3


0  

Rather than mess about with ranges and suffixes, NSString has a method that treats an NSString as a path and returns an extension, it's called pathExtension.

NSString有一个方法将NSString视为路径并返回一个扩展名,而不是乱七八糟的范围和后缀,它被称为pathExtension。

Have a look in the NSString Documentation

查看NSString文档

Once you get the extension you can check it against whatever strings you want.

获得扩展后,您可以根据所需的字符串进行检查。