提问人:Jonathan. 提问时间:5/2/2010 最后编辑:Sazzad Hissain KhanJonathan. 更新时间:10/25/2022 访问量:584833
如何在 Objective-C 中检查一个字符串是否包含另一个字符串?
How do I check if a string contains another string in Objective-C?
问:
如何检查一个字符串 () 是否包含另一个较小的字符串?NSString
我希望有这样的东西:
NSString *string = @"hello bla bla";
NSLog(@"%d",[string containsSubstring:@"hello"]);
但我能找到的最接近的是:
if ([string rangeOfString:@"hello"] == 0) {
NSLog(@"sub string doesnt exist");
}
else {
NSLog(@"exists");
}
无论如何,这是查找字符串是否包含另一个字符串的最佳方法吗?
答:
NSString *string = @"hello bla bla";
if ([string rangeOfString:@"bla"].location == NSNotFound) {
NSLog(@"string does not contain bla");
} else {
NSLog(@"string contains bla!");
}
关键是注意到返回一个结构,文档说如果“大海捞针”不包含“针”,它会返回结构。rangeOfString:
NSRange
{NSNotFound, 0}
如果您使用的是 iOS 8 或 OS X Yosemite,您现在可以执行以下操作: *(注意:如果在 iOS7 设备上调用此代码,这将使您的应用程序崩溃)。
NSString *string = @"hello bla blah";
if ([string containsString:@"bla"]) {
NSLog(@"string contains bla!");
} else {
NSLog(@"string does not contain bla");
}
(这也是它在 Swift 中的工作方式)
评论
[string rangeOfString:@"bla"].location != NSNotFound
nil
对于 iOS 8.0+ 和 macOS 10.10+,您可以使用 NSString 的原生 containsString:
。
对于旧版本的 iOS 和 macOS,您可以为 NSString 创建自己的(过时)类别:
@interface NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring;
@end
// - - - -
@implementation NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring
{
NSRange range = [self rangeOfString : substring];
BOOL found = ( range.location != NSNotFound );
return found;
}
@end
注意:请观察下面丹尼尔·加拉斯科(Daniel Galasko)关于命名的评论
评论
return [self rangeOfString:substring].location != NSNotFound;
NSString *myString = @"hello bla bla";
NSRange rangeValue = [myString rangeOfString:@"hello" options:NSCaseInsensitiveSearch];
if (rangeValue.length > 0)
{
NSLog(@"string contains hello");
}
else
{
NSLog(@"string does not contain hello!");
}
您也可以使用以下方法:
if (rangeValue.location == NSNotFound)
{
NSLog(@"string does not contain hello");
}
else
{
NSLog(@"string contains hello!");
}
Oneliner(代码量较小。DRY,因为你只有一个):NSLog
NSString *string = @"hello bla bla";
NSLog(@"String %@", ([string rangeOfString:@"bla"].location == NSNotFound) ? @"not found" : @"cotains bla");
P i 解决方案的一个改进版本,即 NSString 上的一个类别,它不仅可以判断一个字符串是否在另一个字符串中找到,而且还可以通过引用获取范围,它是:
@interface NSString (Contains)
-(BOOL)containsString: (NSString*)substring
atRange:(NSRange*)range;
-(BOOL)containsString:(NSString *)substring;
@end
@implementation NSString (Contains)
-(BOOL)containsString:(NSString *)substring
atRange:(NSRange *)range{
NSRange r = [self rangeOfString : substring];
BOOL found = ( r.location != NSNotFound );
if (range != NULL) *range = r;
return found;
}
-(BOOL)containsString:(NSString *)substring
{
return [self containsString:substring
atRange:NULL];
}
@end
像这样使用它:
NSString *string = @"Hello, World!";
//If you only want to ensure a string contains a certain substring
if ([string containsString:@"ello" atRange:NULL]) {
NSLog(@"YES");
}
// Or simply
if ([string containsString:@"ello"]) {
NSLog(@"YES");
}
//If you also want to know substring's range
NSRange range;
if ([string containsString:@"ello" atRange:&range]) {
NSLog(@"%@", NSStringFromRange(range));
}
下面是一个复制和粘贴函数片段:
-(BOOL)Contains:(NSString *)StrSearchTerm on:(NSString *)StrText
{
return [StrText rangeOfString:StrSearchTerm
options:NSCaseInsensitiveSearch].location != NSNotFound;
}
评论
由于这似乎是谷歌的一个高排名结果,我想补充一下:
iOS 8 和 OS X 10.10 将 containsString:
方法添加到 .Dave DeLong 针对这些系统的示例的更新版本:NSString
NSString *string = @"hello bla bla";
if ([string containsString:@"bla"]) {
NSLog(@"string contains bla!");
} else {
NSLog(@"string does not contain bla");
}
在 iOS 8 和 Swift 中,我们可以使用方法localizedCaseInsensitiveContainsString
let string: NSString = "Café"
let substring: NSString = "É"
string.localizedCaseInsensitiveContainsString(substring) // true
评论
如果你需要这个,写一次:
NSString *stringToSearchThrough = @"-rangeOfString method finds and returns the range of the first occurrence of a given string within the receiver.";
BOOL contains = [stringToSearchThrough rangeOfString:@"occurence of a given string"].location != NSNotFound;
如果不为区分大小写的字符串而烦恼。 尝试一次。
NSString *string = @"Hello World!";
if([string rangeOfString:@"hello" options:NSCaseInsensitiveSearch].location !=NSNotFound)
{
NSLog(@"found");
}
else
{
NSLog(@"not found");
}
NSString *categoryString = @"Holiday Event";
if([categoryString rangeOfString:@"Holiday"].location == NSNotFound)
{
//categoryString does not contains Holiday
}
else
{
//categoryString contains Holiday
}
请使用此代码
NSString *string = @"hello bla bla";
if ([string rangeOfString:@"bla"].location == NSNotFound)
{
NSLog(@"string does not contain bla");
}
else
{
NSLog(@"string contains bla!");
}
所以就我个人而言,我真的很讨厌,但理解它的必要性。NSNotFound
但有些人可能不理解与 NSNotFound 进行比较的复杂性
例如,以下代码:
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
if([string rangeOfString:otherString].location != NSNotFound)
return YES;
else
return NO;
}
有它的问题:
1)显然,如果此代码会崩溃。一个简单的测试是:otherString = nil
NSLog(@"does string contain string - %@", [self doesString:@"hey" containString:nil] ? @"YES": @"NO");
结果!!崩溃!!
2) 对于刚接触 objective-c 的人来说,不太明显的是,相同的代码在 .
例如,以下代码:string = nil
NSLog(@"does string contain string - %@", [self doesString:nil containString:@"hey"] ? @"YES": @"NO");
和这个代码:
NSLog(@"does string contain string - %@", [self doesString:nil containString:nil] ? @"YES": @"NO");
两者都会导致
does string contains string - YES
这显然不是你想要的。
因此,我认为有效的更好的解决方案是使用 rangeOfString 返回 0 长度的事实,因此更好、更可靠的代码是这样的:
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
if(otherString && [string rangeOfString:otherString].length)
return YES;
else
return NO;
}
或者简单地说:
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
return (otherString && [string rangeOfString:otherString].length);
}
对于情况 1 和 2,将返回
does string contains string - NO
那是我的 2 美分;-)
请查看我的 Gist 以获取更多有用的代码。
试试这个,
NSString *string = @"test Data";
if ([[string lowercaseString] rangeOfString:@"data"].location == NSNotFound)
{
NSLog(@"string does not contain Data");
}
else
{
NSLog(@"string contains data!");
}
如果是 swift,则可以使用
let string = "Package #23"
if string.containsString("Package #") {
//String contains substring
}
else {
//String does not contain substring
}
最佳解决方案。就这么简单!如果你想找到一个词或 字符串的一部分。您可以使用此代码。在此示例中,我们将检查 word 的值是否包含“acter”。
NSString *word =@"find a word or character here";
if ([word containsString:@"acter"]){
NSLog(@"It contains acter");
} else {
NSLog (@"It does not contain acter");
}
在 Swift 4 中:
let a = "Hello, how are you?"
a.contains("Hello") //will return true
第一个字符串包含或不包含第二个字符串,
NSString *first = @"Banana";
NSString *second = @"BananaMilk";
NSRange range = [first rangeOfString:second options:NSCaseInsensitiveSearch];
if (range.length > 0) {
NSLog(@"Detected");
}
else {
NSLog(@"Not detected");
}
将选项 NSCaseInsensitiveSearch 与 rangeOfString:options 一起使用:
NSString *me = @"toBe" ;
NSString *target = @"abcdetobe" ;
NSRange range = [target rangeOfString: me options: NSCaseInsensitiveSearch];
NSLog(@"found: %@", (range.location != NSNotFound) ? @"Yes" : @"No");
if (range.location != NSNotFound) {
// your code
}
找到输出结果:是
这些选项可以一起“或”,包括:
NSCase不敏感搜索 NSLiteralSearch NSBackwards搜索等
Swift 4 及更高版本
let str = "Hello iam midhun"
if str.contains("iam") {
//contains substring
}
else {
//doesn't contain substring
}
Objective-C语言
NSString *stringData = @"Hello iam midhun";
if ([stringData containsString:@"iam"]) {
//contains substring
}
else {
//doesn't contain substring
}
试试这个:
斯威夫特 4.1 , 4.2:
let stringData = "Black board"
//swift quick way and case sensitive
if stringData.contains("bla") {
print("data contains string");
}
//case sensitive
if stringData.range(of: "bla",options: .caseInsensitive) != nil {
print("data contains string");
}else {
print("data does not contains string");
}
对于 Objective-C:
NSString *stringData = @"Black board";
//Quick way and case sensitive
if ([stringData containsString:@"bla"]) {
NSLog(@"data contains string");
}
//Case Insensitive
if ([stringData rangeOfString:@"bla" options:NSCaseInsensitiveSearch].location != NSNotFound) {
NSLog(@"data contains string");
}else {
NSLog(@"data does not contain string");
}
评论
if ([string rangeOfString:@"hello"] == 0) {...}
if ([string rangeOfString:@"hello"].length == 0) {...}