Swift string manipulation

I need to do something that seems simple but I can't figure out the right syntax.

Given a string, I need to search for the first occurrence of a substring (not a character). If found, I need to create a new string by removing the part of the old string that is before the substring.

I can't see how this is done in Swift. There is a "firstIndexOf" function, but it only searches for one character at a time.

I also know that there is a "range(of:)" function, but I can't find its documentation, and I don't know what the return type is, or how I would use it.

Thanks, Frank

Answered by Claude31 in 705686022

Is it what you are looking for:

If string is "Hello brave our new world" and substring is "our" you want to get "our new world"

If so, that will do it:

let testStr = "Hello brave our new world"
if let range = testStr.range(of: "our") {
    let index = testStr.distance(from: testStr.startIndex, to: range.lowerBound)
    var newStr = testStr
    newStr.removeFirst(index)
    print("newStr ->", newStr)
}
else {
    print("substring not found")
}
Accepted Answer

Is it what you are looking for:

If string is "Hello brave our new world" and substring is "our" you want to get "our new world"

If so, that will do it:

let testStr = "Hello brave our new world"
if let range = testStr.range(of: "our") {
    let index = testStr.distance(from: testStr.startIndex, to: range.lowerBound)
    var newStr = testStr
    newStr.removeFirst(index)
    print("newStr ->", newStr)
}
else {
    print("substring not found")
}

Yes this works, thanks. I guess range(of:) is an old NSString function that is available, but not documented in Swift.

Swift string manipulation
 
 
Q