How do I check if a string contains another string in Objective-C?

 

In Objective-C, you can use the rangeOfString: method to check if a string contains another string. Here's an example:

objective
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { NSString *mainString = @"Hello, this is a test string."; NSString *substring = @"test"; NSRange range = [mainString rangeOfString:substring]; if (range.location != NSNotFound) { NSLog(@"Substring found at index %lu", (unsigned long)range.location); } else { NSLog(@"Substring not found"); } } return 0; }

In this example, the rangeOfString: method is used to find the range of the substring within the mainString. If the range.location is NSNotFound, it means the substring was not found in the main string. Otherwise, it provides the index where the substring was found.

Remember to import the Foundation framework to use NSString and other Foundation classes.

Comments