Swift : How to get the string before a certain character?

You can do the same with rangeOfString() provided by String class

let string = "Hello Swift"
if let range = string.rangeOfString("Swift") {
   let firstPart = string[string.startIndex..<range.startIndex]
   print(firstPart) // print Hello
}

You can also achieve it with your method substringToIndex()

let string = "Hello Swift"
if let range = string.rangeOfString("Swift") {
   firstPart = string.substringToIndex(range.startIndex)
   print(firstPart) // print Hello
}

Swift 3 UPDATE:

let string = "Hello Swift"
if let range = string.range(of: "Swift") {
    let firstPart = string[string.startIndex..<range.lowerBound]
    print(firstPart) // print Hello
}

Hope this can help you ;)


Use componentsSeparatedByString() as shown below:

var delimiter = " "
var newstr = "token0 token1 token2 token3"
var token = newstr.components(separatedBy: delimiter)
print (token[0])

Or to use your specific case:

var delimiter = " token1"
var newstr = "token0 token1 token2 token3"
var token = newstr.components(separatedBy: delimiter)
print (token[0])

Following up on Syed Tariq's answer: If you only want the string before the delimiter (otherwise, you receive an array [String]):

var token = newstr.components(separatedBy: delimiter).first

Tags:

Ios

Swift