What is the more elegant way to remove all characters after specific character in the String
object in Swift?
Suppose that I have the following string: str.str
and I need to remove the .str
from it. How can I do it?
Thanks in advance.
Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
To remove everything before the first occurrence of the character '-' in a string, pass the character '-' as a separator in the partition() function. Then assign the part after the separator to the original string variable. It will give an effect that we have deleted everything before the character '-' in a string.
The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.
You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.
Here is a way to do it:
var str = "str.str" if let dotRange = str.rangeOfString(".") { str.removeRange(dotRange.startIndex..<str.endIndex) }
Update In Swift 3 it is:
var str = "str.str" if let dotRange = str.range(of: ".") { str.removeSubrange(dotRange.lowerBound..<str.endIndex) }
I think this is better approach:
Update with Swift 4: (substring is now deprecated)
let smth = "element=value" if let index = (smth.range(of: "=")?.upperBound) { //prints "value" let afterEqualsTo = String(smth.suffix(from: index)) //prints "element=" let beforeEqualsToContainingSymbol = String(smth.prefix(upTo: index)) } if let index = (smth.range(of: "=")?.lowerBound) { //prints "=value" let afterEqualsToContainingSymbol = String(smth.suffix(from: index)) //prints "element" let beforeEqualsTo = String(smth.prefix(upTo: index)) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With