【发布时间】:2018-02-08 01:33:30
【问题描述】:
我有一个 macOS 应用程序。我需要从任何NSURL 中删除方案和www 部分。这是我想出的:
// For testing purposes.
NSString *blogID = @"https://www.testing1234.tumblr.com";
// Create the corrected link string.
NSString *correctLink;
// Convert the string to a url.
NSURL *url = [NSURL URLWithString:blogID];
// Check if the url has a scheme.
if ([url scheme] != nil) {
correctLink = [url host];
} else {
correctLink = blogID;
}
// Ensure there are enough characters before
// performing the necessary 'www.' checks.
if ([correctLink length] > 4) {
// Remove the first instance of 'www.'
// from the blog url link string.
if ([[correctLink substringToIndex:4] containsString:@"www."]) {
correctLink = [correctLink substringFromIndex:4];
}
}
NSLog(@"correctLink: %@", correctLink);
我的问题是:如何可靠地删除字符串的 www 部分?对于初学者,www 没有不同的变体,例如www2? NSURL 是否有任何方法可以让我检测到字符串的 www 部分? (就像我可以通过调用scheme 来检测字符串的http:// 部分一样)。
更新
我不能使用stringByReplacingOccurrencesOfString,因为它会替换所有出现的www。因此,如果 url 恰好是 www.testsitewww.tumblr.com,那么它将变为 testsite.tumblr.com。这不是我想要的,我只想删除第一次出现的www(或任何其他变体,例如www2)。
谢谢,丹。
【问题讨论】:
标签: objective-c nsstring nsurl host