如何在特定字符后删除字符串中的字符?

时间:2015-09-29 20:16:48

标签: string swift

给定一个字符串,如何截断一个特定字符后面的所有字符?

例如我有一个网址:

http://pics.v6.top.rbk.ru/v6_top_pics/resized/250xH/media/img/7/92/754435534528927.jpg"><div>Some text</div>"

我想删除"后的所有字符,包括"字符。

3 个答案:

答案 0 :(得分:1)

extension String {
    mutating func stripFromCharacter(char:String) {
        let c = self.characters
        if let ix = c.indexOf("\"") {
            self = String(c.prefixUpTo(ix))
        }
    }
}

以下是如何使用它:

var s = "http://pics.v6.top.rbk.ru/v6_top_pics/resized/250xH/media/img/7/92/754435534528927.jpg\"><div>Some text</div>"
s.stripFromCharacter("\"")

答案 1 :(得分:0)

可能是最愚蠢的方式,但它有效。

let a = "http://pics.v6.top.rbk.ru/v6_top_pics/resized/250xH/media/img/7/92/754435534528927.jpg\"" + "><div>Some text</div>"
print(a)
var new = ""
for char in a.characters{
    if char == "\""{ break }
    new.append(char)
}

print(new)

答案 2 :(得分:0)

也许您只想使用NSDataDetectors

E.G。类似的东西:

let input = "http://pics.v6.top.rbk.ru/v6_top_pics/resized/250xH/media/img/7/92/754435534528927.jpg"><div>Some text</div>""
let detector = try! NSDataDetector(types: NSTextCheckingType.Link.rawValue)
let matches = detector.matchesInString(input, options: [], range: NSMakeRange(0, input.characters.count))

for match in matches {
    let url = (input as NSString).substringWithRange(match.range)
    print(url)
}

可以找到更多信息in this HackingWithSwift blog post