如何查看NSString是否以某个其他字符串开头?

Rob*_*Rob 150 iphone objective-c nsstring nsmutablestring ios

我试图检查我将用作URL的字符串是否以http开头.我现在试图检查的方式似乎不起作用.这是我的代码:

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];
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Cyr*_*lle 327

试试这个:if ([myString hasPrefix:@"http"]).

顺便说一句,你的测试应该是!= NSNotFound代替== NSNotFound.但是说你的网址是ftp://my_http_host.com/thing,它会匹配,但不应该.


Jon*_*asG 22

我喜欢用这个方法:

if ([[temp substringToIndex:4] isEqualToString:@"http"]) {
  //starts with http
}
Run Code Online (Sandbox Code Playgroud)

甚至更容易:

if ([temp hasPrefix:@"http"]) {
    //do your stuff
}
Run Code Online (Sandbox Code Playgroud)

  • @JonasG - 是的,你对substringToIndex的行为是正确的.但请注意,索引4实际上是第5个字符; index 0是第一个字符.我错误地认为substringToIndex包含索引指定的字符,但它没有.当涉及用户输入时,区分大小写是相关的,我相信这个问题提示了.考虑"HTTP:// WWW ......"的情况.但最大的问题是,当遇到"ftp"或少于4个字符的字符串时,建议的解决方案将抛出异常.hasPrefix方法没有相同的问题. (3认同)
  • 如果临时字符串少于5个字符,则会崩溃.指数从0开始.所以这不是一个好的答案.此外,该示例的字符数不匹配:"http"没有5个字符.还应考虑不区分大小写. (2认同)

bob*_*ics 6

如果您正在检查"http:",您可能需要不区分大小写的搜索:

NSRange prefixRange = 
    [temp rangeOfString:@"http" 
                options:(NSAnchoredSearch | NSCaseInsensitiveSearch)];
if (prefixRange.location == NSNotFound)
Run Code Online (Sandbox Code Playgroud)