How to see if an NSString starts with a certain other string?
I am trying to check to see if a string that I am going to use as URL starts with http. The way I am trying to check right now doesn't seem to be working. Here is my code:
NSMutableString *temp = [[NSMutableString alloc] initWithString:@"http://"];
if ([businessWebsite rangeOfString:@"http"].location == NSNotFound){
NSString *temp2 = [[NSString alloc] init];
temp2 = businessWebsite;
[temp appendString:temp2];
businessWebsite = temp2;
NSLog(@"Updated BusinessWebsite is: %@", businessWebsite);
}
[web setBusinessWebsiteUrl:businessWebsite];
Any ideas?
Solution 1:
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.
Solution 2:
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
}
Solution 3:
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)
Solution 4:
Swift version:
if line.hasPrefix("#") {
// checks to see if a string (line) begins with the character "#"
}