To check if a string contains another string in objective-c, we can use the rangeOfString: instance method where it returns the {NSNotFound, 0} if a 'searchString' is not found or empty (""). Output: string contains you!
You can check if [string length] == 0 . This will check if it's a valid but empty string (@"") as well as if it's nil, since calling length on nil will also return 0.
A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.
If you create an object using a method that begins with init, new, copy, or mutableCopy, then you own that object and are responsible for releasing it (or autoreleasing it) when you're done with it. If you create an object using any other method, that object is autoreleased, and you don't need to release it.
Try this: if ([myString hasPrefix:@"http"])
.
By the way, your test should be != NSNotFound
instead of == NSNotFound
. But say your URL is ftp://my_http_host.com/thing
, it'll match but shouldn't.
I like to use this method:
if ([[temp substringToIndex:4] isEqualToString:@"http"]) {
//starts with http
}
or even easier:
if ([temp hasPrefix:@"http"]) {
//do your stuff
}
If you're checking for "http:" you'll probably want case-insensitive search:
NSRange prefixRange =
[temp rangeOfString:@"http"
options:(NSAnchoredSearch | NSCaseInsensitiveSearch)];
if (prefixRange.location == NSNotFound)
Swift version:
if line.hasPrefix("#") {
// checks to see if a string (line) begins with the character "#"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With