从 URL 字符串中解析域名

发布于 2024-08-22 17:59:35 字数 148 浏览 4 评论 0原文

如何在 Objective-C 中解析域名?

例如,如果我的字符串值为“http://www.google.com”,我想解析出字符串“谷歌”

How would I parse a domain name in Objective-C?

For example if my string value was "http://www.google.com" I would like to parse out the string "google"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

口干舌燥 2024-08-29 17:59:35

我认为这个问题有点无效。主机由其 FQDN(完全限定域名)决定,在您的示例中,其为 www.google.com。它与 mail.google.comwww.google.infogoogle.com 不同。单独列出“google”并不是一件小事,从 URL 的角度来看也没有多大意义。

如果您想或多或少地智能地解析 URL,我认为您可以执行以下操作:

  1. 使用 NSURL 的 -host 方法来正确剥离方案和路径/查询。
  2. 使用 NSString 的 -componentsSeparatedByString: 方法获取域名“组件”的数组。
  3. 忽略最后一个组件。
  4. 如果只剩下一个组件(或者可能足以获取倒数第二个组件),那么您就完成了。
  5. 如果第一个组件包含“www”,如www3、“ftp”、“mail”或类似的内容,如果您愿意,您也可以忽略它。其余的可能会感兴趣,具体取决于您的需要。
  6. 针对一万个 URL 测试您的算法,以了解此任务的徒劳性;)

I think the question is a tiny bit invalid. A host is determined by its FQDN (fully qualified domain name) which, in your example, is www.google.com. It's not the same as mail.google.com or www.google.info or google.com. To single out "google" is not trivial and does not make much sense from URL perspective.

If you'd like to just parse the URL more-or-less intelligently, I think you can do the following:

  1. Use NSURL's -host method to get the scheme and path/query stripped correctly.
  2. Use NSString's -componentsSeparatedByString: method to get an array of the domain name's "components".
  3. Ignore the last component.
  4. If there's only one component left (or it may be enough to take the second-last component), you're done.
  5. If the first component contains "www" like www3, "ftp", "mail" or something of their kind, you can ignore it too if you like. The rest may be of interest, depending on your needs.
  6. Test your algorithm against ten thousand URLs to get a sense of futility of this task ;)
不羁少年 2024-08-29 17:59:35

在 iOS 7 中,您可以使用 NSURLComponents 类:

NSURLComponents *components = [[NSURLComponents alloc] initWithString:@"http://stackoverflow.com/questions/2333972/objective-c-parse-domain-name-from-url-string"];
NSAssert([components.host isEqualToString:@"stackoverflow.com"], nil);

In iOS 7 you can use the NSURLComponents class:

NSURLComponents *components = [[NSURLComponents alloc] initWithString:@"http://stackoverflow.com/questions/2333972/objective-c-parse-domain-name-from-url-string"];
NSAssert([components.host isEqualToString:@"stackoverflow.com"], nil);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文