2

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");
 }
Popeye
  • 11,839
  • 9
  • 58
  • 91
user2064546
  • 21
  • 1
  • 1
  • 4
  • Possible duplicate? http://stackoverflow.com/questions/2753956/how-do-i-check-if-a-string-contains-another-string-in-objective-c – Josip B. Apr 08 '14 at 12:28
  • You can use regex if rangeOfString don't work ;) – Clad Clad Apr 08 '14 at 12:29
  • Welcome to stackoverflow. Please note just because you are using the `xcode IDE` doesn't mean you should be using the `xcode` tag. The `xcode` tag is reserved for issues relating to the `xcode IDE` itself not issues you are having writing code in the `xcode IDE`. When asking a question if you think you need to use the `xcode` tag more than likely you shouldn't be using it at all. – Popeye Apr 08 '14 at 12:29

4 Answers4

7
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

Community
  • 1
  • 1
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
1

Try following:

 NSString *data = @"red manual";

 if ([data rangeOfString:@"red ma" options:NSCaseInsensitiveSearch].location == NSNotFound) {
    NSLog(@"not matched");
 }
 else {
    NSLog(@"matched");
}
Uniruddh
  • 4,427
  • 3
  • 52
  • 86
  • Which way is the check happening? Is it checking if @"red ma" contains any of the characters from data or, is it checking if data has any of the characters from @"red ma"? – Supertecnoboff Feb 17 '16 at 15:25
  • 1
    @Supertecnoboff: this will check if data has @"red ma" string in it or not. – Uniruddh Feb 18 '16 at 05:51
0

Have a look at this great NSHipster page about NSRange, it should explain things a bit better than Apple's documentation.

tagyro
  • 1,638
  • 2
  • 21
  • 36
0
NSString *string = @"red manual";
if([string rangeOfString:@"red ma"].location == NSNotFound)
{
    NSLog(@"not found");
}
else
{
     NSLog(@"found");
}
Bipin Patel
  • 228
  • 1
  • 5