4

How can I check if an NSString contains another substring, at which point it will return a Boolean Value.

This is what I'm thinking of:

If myString.contains("string") then
{
   //Stuff Happens
}

But, from the research I've done, it seems as if Obj-C has no function for this. This Wikipedia article gives numerous string functions, their differences, and all in different languages, but I see no Obj-C support for any Contain Function.

Does anyone know of a simple-to-use function like the once above (which is similar to the C# and VB.NET function)?

Would a "Find" Function work? If so, how?

If this is not supported in Obj-C, is there a workaround I can use?

Any help is very appreciated.

Dr.Kameleon
  • 21,495
  • 19
  • 103
  • 208
Sam Spencer
  • 8,158
  • 12
  • 70
  • 130

5 Answers5

12
if ([myString rangeOfString:@"string"].location != NSNotFound)
{
    // Stuff happens
}
Andrew Madsen
  • 20,769
  • 5
  • 52
  • 92
4
NSString *someString = @"Time for an egg hunt";

if ( [someString rangeOfString:@"egg" options:NSCaseInsensitiveSearch].location != NSNotFound ) {
  NSLog( @"Found it!" );
}
Frank
  • 3,386
  • 1
  • 20
  • 23
4

If you want to be case insensitive.

NSRange range = [string rangeOfString:@"string" options:NSCaseInsensitiveSearch];
if (range.location != NSNotFound)
{
    return range.location;
}
else
{
    return nil;
}

Documentation

P.J.Radadiya
  • 1,372
  • 10
  • 16
giannis christofakis
  • 7,151
  • 4
  • 48
  • 63
2

Create a NSString category, and put that in...

Code :

- (BOOL)contains:(NSString *)str
{
    NSRange aRange = [self rangeOfString:str];

    return (aRange.location!=NSNotFound);
}

Usage :

NSString* testStr = @"This is my string";

if ([testStr contains:@"is"])
{
     // do something
}
Dr.Kameleon
  • 21,495
  • 19
  • 103
  • 208
1
if([string rangeOfString:substring].length > 0)
    ...
warrenm
  • 28,472
  • 4
  • 71
  • 102