如何检查NSString是否包含具有特定地址的网址

时间:2017-12-11 16:43:46

标签: ios objective-c nsstring

我一直在寻找和尝试不同的事情,但是做得很少。

我正在尝试使用某人复制的URL,即:https://website/u/drksndrs,并将其与if语句进行比较,基本上说复制的字符串是否匹配https://website/u/前缀,然后继续执行程序。在u /之后根据他们的ID搜索不同的用户。这是我现在的代码。

NSString *latest = [UIPasteboard generalPasteboard].string;
NSString *prefix = @"https://www.website.com/u/";
NSRange textRange = [latest rangeOfString:prefix];
if (textRange.location != NSNotFound) {
    NSLog(@"the prefix matches!");
    [self performOperation];
} else {
    NSLog(@"This doesn't match the https://www.website.com/u/ prefix.");
}

1 个答案:

答案 0 :(得分:4)

您应该检查textRange.location == 0是否是前缀。更好的是,使用hasPrefix:方法。

NSString *latest = [UIPasteboard generalPasteboard].string;
NSString *prefix = @"https://www.website.com/u/";
if ([latest hasPrefix:prefix]) {
    NSLog(@"the prefix matches!");
    [self performOperation];
} else {
    NSLog(@"This doesn't match the https://www.website.com/u/ prefix.");
}