How to check string contains characters?

How to check a string contains a particular character or word. In my case I have a string " red manual ". Here I have to check for "red ma" in my string. I tried it by using range of string methods but its not satisfying the condition.

Here is my code

 NSString *string = @"red manual";
 NSRange newlineRange = [string rangeOfString:@"red ma"];
 if(newlineRange.location != NSNotFound) 
 {
     NSLog(@"found");
 }
 else
 {
     NSLog(@"not found");
 }

NSString *string = @"hello bla bla";
if ([string rangeOfString:@"bla"].location == NSNotFound) {
  NSLog(@"string does not contain bla");
} else {
  NSLog(@"string contains bla!");
}

The key is noticing that rangeOfString : returns an NSRange struct , and the documentation says that it returns the struct {NSNotFound, 0} if the "haystack" does not contain the "needle".

And if you're on iOS 8 or OS X Yosemite, you can now do:

NSString *string = @"hello bla blah";
if ([string containsString:@"bla"]) {
  NSLog(@"string contains bla!");
} else {
  NSLog(@"string does not contain bla");
}

it is answered here


试试以下内容

 NSString *data = @"red manual";

 if ([data rangeOfString:@"red ma" options:NSCaseInsensitiveSearch].location == NSNotFound) {
    NSLog(@"not matched");
 }
 else {
    NSLog(@"matched");
}

看看这个关于NSRange的NSHipster页面,它应该解释一些比Apple的文档更好的东西。

链接地址: http://www.djcxy.com/p/74002.html

上一篇: 搜索另一个数组中的数组元素

下一篇: 如何检查字符串包含字符?