Reputation: 6723
Given a string, how do I truncate all characters following one particular character?
For example I have a url:
http://pics.v6.top.rbk.ru/v6_top_pics/resized/250xH/media/img/7/92/754435534528927.jpg"><div>Some text</div>"
I want to strip all characters after the "
, including the "
character.
Upvotes: 0
Views: 1922
Reputation: 534958
extension String {
mutating func stripFromCharacter(char:String) {
let c = self.characters
if let ix = c.indexOf("\"") {
self = String(c.prefixUpTo(ix))
}
}
}
And here's how to use it:
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("\"")
Upvotes: 1
Reputation: 89509
Maybe you simply want to use NSDataDetectors?
E.G. something like:
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)
}
More info can be found in this HackingWithSwift blog post.
Upvotes: 0
Reputation: 3433
Probably the dumbest way to do it but it works.
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)
Upvotes: 0