Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the more elegant way to remove all characters after specific character in the String object in Swift

Tags:

swift

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.

like image 728
FrozenHeart Avatar asked Dec 01 '14 10:12

FrozenHeart


People also ask

How do you remove all of a certain character in a string?

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.

How do I remove all characters from a string before a specific character?

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.

How do I remove a string after a character?

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.

How do I remove an element from a 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.


2 Answers

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) } 
like image 82
Kirsteins Avatar answered Nov 16 '22 02:11

Kirsteins


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)) } 
like image 21
Dominik Bucher Avatar answered Nov 16 '22 00:11

Dominik Bucher