我有一个值为
http://digg.com/news/business/24hr
怎么才能在3级之前获得所有东西?
http://digg.com/news/
我有一个值为
http://digg.com/news/business/24hr
怎么才能在3级之前获得所有东西?
http://digg.com/news/
请注意,这不完全是第三级。一个 URL 是这样拆分的:
http
)://
分隔符username:password@hostname
)digg.com
):80
例如,在域名之后)/news/business/24hr
)?foo=bar&baz=frob
)#foobar
)。“功能齐全”的 URL 如下所示:
http://foobar:nicate@example.com:8080/some/path/file.html;params-here?foo=bar#baz
NSURL
具有广泛的访问器。您可以在该类的文档中查看它们NSURL
,部分访问 URL 的部分。快速参考:
-[NSURL scheme]
= http-[NSURL resourceSpecifier]
=(从 // 到 URL 末尾的所有内容)-[NSURL user]
= 富吧-[NSURL password]
= 好-[NSURL host]
= example.com-[NSURL port]
= 8080-[NSURL path]
= /some/path/file.html-[NSURL pathComponents]
= @["/", "some", "path", "file.html"] (注意开头的 / 是它的一部分)-[NSURL lastPathComponent]
= 文件.html-[NSURL pathExtension]
= html-[NSURL parameterString]
= 参数-这里-[NSURL query]
= 富=酒吧-[NSURL fragment]
=巴兹但是,您想要的是这样的:
NSURL* url = [NSURL URLWithString:@"http://digg.com/news/business/24hr"];
NSString* reducedUrl = [NSString stringWithFormat:
@"%@://%@/%@",
url.scheme,
url.host,
url.pathComponents[1]];
对于您的示例 URL,您似乎想要的是协议、主机和第一个路径组件。(返回的数组中索引 0 处的元素-[NSString pathComponents]
只是“/”,因此您需要索引 1 处的元素。其他斜杠被丢弃。)