Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all characters after a certain character from a string in Swift [duplicate]

I have a textField and I would like to remove all character after a certain character.

For instance if what I have in the textField is the word Orange and I want to remove all characters after the n I would like to get Ora after the deletion.

How can I delete all characters after a certain character from a string in Swift?

Thanks

like image 691
fs_tigre Avatar asked Aug 27 '16 19:08

fs_tigre


2 Answers

You can use StringProtocol method range(of string:), get the resulting range lowerBound, create a PartialRangeUpTo with it and subscript the original string:

Swift 4 or later

let word = "orange"
if let index = word.range(of: "n")?.lowerBound {
    let substring = word[..<index]                 // "ora"
    // or  let substring = word.prefix(upTo: index) // "ora"
    // (see picture below) Using the prefix(upTo:) method is equivalent to using a partial half-open range as the collection’s subscript. 
    // The subscript notation is preferred over prefix(upTo:).

    let string = String(substring)
    print(string)  // "ora"
}

enter image description here

like image 172
Leo Dabus Avatar answered Oct 26 '22 11:10

Leo Dabus


You could do it like this:

guard let range = text.rangeOfString("Your String or Character here") else {
    return the text 
}

return text.substringToIndex(range.endIndex)
// depending on if you want to delete before a certain string, you would use range.startIndex
like image 22
cloudcal Avatar answered Oct 26 '22 12:10

cloudcal