(Swift)解析字符串的函数(from-to)

时间:2015-07-28 14:23:04

标签: string swift parsing

还有其他方法可以解析字符串"从 - 到"? 我的意思是当我们需要一个值时,我们知道它之前和之后的字符串。 我刚刚创建了

这样的功能
func parser(textToParse:String, strFrom:String, strTo:String) -> String {
        return textToParse.componentsSeparatedByString(strFrom)[1].componentsSeparatedByString(strTo)[0]
    }

它使用像

var s=parser("abc", strFrom: "a", strTo: "c")
//s will be "b"

1 个答案:

答案 0 :(得分:0)

You could do something like this using substringWithRange:

func substringBetween(start: String, and end: String) -> String? {
    if let startIndex = rangeOfString(start, options: .LiteralSearch, range: nil, locale: nil)?.endIndex,
           endIndex = rangeOfString(end, options: .LiteralSearch, range: startIndex..<self.endIndex, locale: nil)?.startIndex {
        return substringWithRange(startIndex..<endIndex)
    } else {
        return nil
    }
}