Delete All Characters After a Certain Character from a String in Swift

Delete all characters after a certain character from a string in Swift

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"
}

Sample Image

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

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)
}

Get the string up to a specific character

Expanding on @appzYourLife answer, the following will also trim off the whitespace characters after removing everything after the @ symbol.

import Foundation

var str = "hello, how are you @tom"

if str.contains("@") {
let endIndex = str.range(of: "@")!.lowerBound
str = str.substring(to: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
}
print(str) // Output - "hello, how are you"

UPDATE:

In response to finding the last occurance of the @ symbol in the string and removing it, here is how I would approach it:

var str = "hello, how are you @tom @tim?"
if str.contains("@") {
//Reverse the string
var reversedStr = String(str.characters.reversed())
//Find the first (last) occurance of @
let endIndex = reversedStr.range(of: "@")!.upperBound
//Get the string up to and after the @ symbol
let newStr = reversedStr.substring(from: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)

//Store the new string over the original
str = String(newStr.characters.reversed())
//str = "hello, how are you @tom"
}

Or looking at @appzYourLife answer use range(of:options:range:locale:) instead of literally reversing the characters

var str = "hello, how are you @tom @tim?"
if str.contains("@") {
//Find the last occurrence of @
let endIndex = str.range(of: "@", options: .backwards, range: nil, locale: nil)!.lowerBound
//Get the string up to and after the @ symbol
let newStr = str.substring(from: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)

//Store the new string over the original
str = newStr
//str = "hello, how are you @tom"
}

As an added bonus, here is how I would approach removing every @ starting with the last and working forward:

var str = "hello, how are you @tom and @tim?"
if str.contains("@") {

while str.contains("@") {
//Reverse the string
var reversedStr = String(str.characters.reversed())
//Find the first (last) occurance of @
let endIndex = reversedStr.range(of: "@")!.upperBound
//Get the string up to and after the @ symbol
let newStr = reversedStr.substring(from: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)

//Store the new string over the original
str = String(newStr.characters.reversed())
}
//after while loop, str = "hello, how are you"
}

Delete all character after particular character in string

"word" is a String Variable here where you can apply your needs and "T" is a character after which you want to delete all other characters

if let index = word.range(of: "T")?.lowerBound {
let substring = word[..<index]
let string = String(substring)
self.birthdayField.text = string
}

How to remove specific characters or words from a string in swift?

I think this will be faster with a regex solution:

//use NSMutableString so the regex.replaceMatches later will work
var myString:NSMutableString = "43321 This is example hahaha 4356-13"

//add more words to match by using | operator e.g. "[0-9]{1,}|apple|orange"
//[0-9]{1,} simply removes all numbers but is more efficient than [0-9]
let regexPattern = "[0-9]{1,}|apple"

//caseInsensitive or the regex will be much longer
let regex = try NSRegularExpression(pattern: regexPattern, options: .caseInsensitive)

var matches = regex.matches(in: myString as String, options: .withoutAnchoringBounds, range: range)
regex.replaceMatches(in: myString, options: .withoutAnchoringBounds, range: range, withTemplate: "")

print(myString) // This is example hahaha -

Subsequent Strings

var testString3: NSMutableString = "apple banana horse"
matches = regex.matches(in: testString3 as String, options: .withoutAnchoringBounds, range: range)
regex.replaceMatches(in: testString3, options: .withoutAnchoringBounds, range: range, withTemplate: "")
print(testString3) // banana horse

swift: how can I delete a specific character?

If you need to remove characters only on both ends, you can use stringByTrimmingCharactersInSet(_:)

let delCharSet = NSCharacterSet(charactersInString: "! ")

let s1 = "! aString! !"
let s1Del = s1.stringByTrimmingCharactersInSet(delCharSet)
print(s1Del) //->aString

let s2 = "! anotherString !! aString! !"
let s2Del = s2.stringByTrimmingCharactersInSet(delCharSet)
print(s2Del) //->anotherString !! aString

If you need to remove characters also in the middle, "reconstruct from the filtered output" would be a little bit more efficient than repeating single character removal.

var tempUSView = String.UnicodeScalarView()
tempUSView.appendContentsOf(s2.unicodeScalars.lazy.filter{!delCharSet.longCharacterIsMember($0.value)})
let s2DelAll = String(tempUSView)
print(s2DelAll) //->anotherStringaString

If you don't mind generating many intermediate Strings and Arrays, this single liner can generate the expected output:

let s2DelAll2 = s2.componentsSeparatedByCharactersInSet(delCharSet).joinWithSeparator("")
print(s2DelAll2) //->anotherStringaString

Remove all instances of (substring plus next character) in string in Swift

You can make use of removing a substring in a couple ways:

while let range = str.range(of: "!") {
str.removeSubrange(range.lowerBound...range.upperBound)
}

or

while let index = str.index(of: "!") {
let end = str.index(after: index)
str.removeSubrange(index...end)
}

By using ... you will remove one character beyond the range of the character you are looking for.

You'll probably want to add a check that ! is not the last character of a string.

Remove the first six characters from a String (Swift)

length is the number of characters you want to remove (6 in your case)

extension String {

func toLengthOf(length:Int) -> String {
if length <= 0 {
return self
} else if let to = self.index(self.startIndex, offsetBy: length, limitedBy: self.endIndex) {
return self.substring(from: to)

} else {
return ""
}
}
}

Sample Image
Sample Image



Related Topics



Leave a reply



Submit