String matching and comparison in Objective-C (Cocoa Framework)

This snippet shows how to search for a string within another string and how to check if two strings are equal.

NSString* needle = @"hello";
NSString* haystack = @"hello world";

NSRange matching = [haystack rangeOfString : needle];

// Searching for a string within another string
if(matching.location == NSNotFound){
	// Needle not found in haystack
} else {
	// Needle found in haystack
}

// Checking for equality
if([needle isEqualToString:@"hello"]){
	// Needle is equal to "hello"
} else {
	// Needle is not equal to "hello"
}
This entry was posted in Objective-C and tagged , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?