2016-09-19 71 views
1

我有一個文件路徑...路徑提取SWIFT 3.0

/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

從'leftSide',得到的範圍內 「」並獲得它後面的部分? – Larme

+0

如果您需要,您的一個班輪是對自定義功能的呼叫... – Wain

回答

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) 
} 
0

Bon,

Sparky感謝您的回答。我結束了這個..這是相同的,但不同的。

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("") 
} 
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"