【发布时间】:2013-11-26 16:03:38
【问题描述】:
我有一个网址
http://www.hdwallpapers.in/walls/honda_v4_concept_widescreen_bike-wide.jpg
我想提取文件名为“honda_v4_concept_widescreen_bike-wide.jpg”
我该怎么做?
【问题讨论】:
标签: nsurl
我有一个网址
http://www.hdwallpapers.in/walls/honda_v4_concept_widescreen_bike-wide.jpg
我想提取文件名为“honda_v4_concept_widescreen_bike-wide.jpg”
我该怎么做?
【问题讨论】:
标签: nsurl
下面的代码应该可以工作。更新了它,所以我删除了最上面的声明。我本可以使用 C++ 中的 NSString 与 const char * 或 std::string,但认为 C 字符指针非常适合这种情况。
还对其进行了改进,使其具有自己的简洁功能:
-(NSString*) extractFile:(const char*) url
{
NSURL *yourURL = [NSURL URLWithString:
[NSString stringWithCString:url
encoding:NSUTF8StringEncoding]];
return [yourURL lastPathComponent];
}
使用:
const char *path_ = "http://www.hdwallpapers.in/walls/honda_v4_concept_widescreen_bike-wide.jpg";
NSLog(@"\t\tYour Extracted file: \n\t%@", [self extractFile:path_]);
【讨论】:
NSURL.lastPathComponent 甚至可以用于fileReferenceURL 风格的 URL。改用absoluteString 会导致“id=65134...”
只需使用基本名称basename()函数
$url = http://www.fullhdwallpapers.in/wp-content/uploads/2017/01/Logan-Movie-Kid-2017-680x425.jpg
echo basename($url);
【讨论】:
NSURL,这意味着他们想要 Swift 或 Objective-C 中的答案。
斯威夫特 3:
let urlString = "http://www.hdwallpapers.in/walls/honda_v4_concept_widescreen_bike-wide.jpg"
if let url = URL(string: urlString) {
print("file name: \(url.lastPathComponent)")
} else {
print("error - not a valid url!")
}
【讨论】:
下面的代码有效。 absoluteString 在另一个答案中被推荐,但如果文件名中有(例如)空格,它就不能正常工作。
NSString *JPEGfilename = [[yourURL path] lastPathComponent];
【讨论】: