我有一个文件路径......
/acme101/acmeX100/acmeX100.008.png
我可以使用它来获取扩展程序.png in this case
let leftSide = (lhs.fnName as NSString).pathExtension
这是获取文件名acmeX100
let leftSide = (lhs.fnName as NSString).lastPathComponent
但是我想要中间位......在这种情况下是008?
有一个漂亮的衬垫吗?
答案 0 :(得分:2)
假设文件路径采用了这种通用形式,那么(几乎)是一个单行(我喜欢安全地玩):
var filePath = "/acme101/acmeX100/acmeX100.008.png"
func extractComponentBetweenDots(inputString: String) -> String? {
guard inputString.components(separatedBy: ".").count > 2 else { print("Incorrect format") ; return nil } // Otherwise not in the correct format, you caa add other tests
return inputString.components(separatedBy: ".")[inputString.components(separatedBy: ".").count - 2]
}
使用如下:
if let extractedString : String = extractComponentBetweenDots(inputString: filePath) {
print(extractedString)
}
答案 1 :(得分:1)
我想用你问题中的相同技术做一个例子 - 尽管向NSString的向下转换使整个事情变得相当丑陋,但它的工作效率却很高。这是在Swift 3中,但如果需要,可以很容易地将它移植回Swift 2。
func getComponents(from str: String) -> (name: String, middle: String, ext: String) {
let compo = (str as NSString).lastPathComponent as NSString
let ext = compo.pathExtension
let temp = compo.deletingPathExtension as NSString
let middle = temp.pathExtension
let file = temp.deletingPathExtension
return (name: file, middle: middle, ext: ext)
}
let result = getComponents(from: "/acme101/acmeX100/acmeX100.008.png")
print(result.name) // "acmeX100"
print(result.middle) // "008"
print(result.ext) // "png"
如果你只需要中间部分:
func pluck(str: String) -> String {
return (((str as NSString).lastPathComponent as NSString).deletingPathExtension as NSString).pathExtension
}
pluck(str: "/acme101/acmeX100/acmeX100.008.png") // "008"
答案 2 :(得分:0)
Bon,
明智地感谢您的回答。我最终得到了这个......这是相同但又不同的。
func pluck(str:String) -> String {
if !str.isEmpty {
let bitZero = str.characters.split{$0 == "."}.map(String.init)
if (bitZero.count > 2) {
let bitFocus = bitZero[1]
print("bitFocus \(bitFocus)")
return(bitFocus)
}
}
return("")
}