I have got a string range in Swift but I want to extend it on by a few characters but I cannot see how to do this.
Here is my code:
var fullMessage = "This\n is\n my example\n message.\n Thanks Leigh Smith\n and some more characters\n and lots more \n"
var startName = fullMessage.rangeOfString("Leigh")
var endMessage = fullMessage[advance(startName!.endIndex,0)...advance(fullMessage.endIndex,-1)]
var posRange = endMessage.rangeOfString("\n")
var pos = posRange?.startIndex
var xpos = advance(startName!.endIndex, 0)
fullMessage = fullMessage[advance(fullMessage.startIndex, 0)...advance(startName!.endIndex,advance(pos, 0))]
My problem is that fullMessage could contain random numbers of \n. I want to get the string from the start of the fullMessage string until the \n after "Leigh" i.e. "This\n is\n my example\n message.\n Thanks Leigh Smith\n".
My thoughts were to find the next "\n" and then extend the original range. Hopefully there is an easy way of doing this with much nicer code.
Thanks
macaaw
import Foundation
let fullMessage = "This\n is\n my example\n message.\n Thanks Leigh Smith\n and some more characters\n and lots more \n"
extension String {
func sliceAfter(after: String, to: String) -> String {
return rangeOfString(after).flatMap {
rangeOfString(to, range: $0.endIndex..<endIndex).map {
substringToIndex($0.endIndex)
}
} ?? self
}
}
fullMessage.sliceAfter("Leigh", to: "\n") // "This\n is\n my example\n message.\n Thanks Leigh Smith\n"