我有一个macOS应用程序。我需要删除任何NSURL
的方案和www
部分。这是我想出了:在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
)。
谢谢,丹。
@Supertecnoboff更新了代码并进行了测试。请检查一下。 –
完美地工作,正是我需要的。谢谢! – Supertecnoboff