如何检查 NSString 是否具有具有特定地址的 URL

How to check if NSString has a URL with a specific address

我一直在搜索和尝试不同的东西,但人手不足。

我正在尝试使用某人复制的 URL 即:https://website/u/drksndrs and compare it with an if statement basically saying if copied string matches 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.");
}

您应该检查 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.");
}