How to filter characters from a string in Swift 4
Swift 4 makes it a little simpler. Just remove the .characters and use
let myNumbers = myString.filter { "0123456789".contains($0) }
But to really do it properly, you might use the decimalDigits character set...
let digitSet = CharacterSet.decimalDigits
let myNumbers = String(myString.unicodeScalars.filter { digitSet.contains($0) })
Swift - Remove character from string
Swift uses backslash to escape double quotes. Here is the list of escaped special characters in Swift:
\0
(null character)\\
(backslash)\t
(horizontal tab)\n
(line feed)\r
(carriage return)\"
(double quote)\'
(single quote)
This should work:
text2 = text2.replacingOccurrences(of: "\\", with: "", options: NSString.CompareOptions.literal, range: nil)
Looking for the best way to filter text from string in Swift
One way to do this is to first map the strings to a tuple containing the index of the search text in string, and the string itself. Then sort by the index, then map the tuples back to the strings.
let array = ["Anand", "Ani", "Dan", "Eion", "Harsh", "Jocab", "Roshan", "Stewart"]
let searchText = "R"
// compactMap acts as a filter, removing the strings where string.index(of: searchText, options: [.caseInsensitive]) returns nil
let result = array.compactMap { string in string.index(of: searchText, options: [.caseInsensitive]).map { ($0, string) } }
.sorted { $0.0 < $1.0 }.map { $0.1 }
The index(of:options:)
method is taken from this answer here.
For Swift 4.x:
extension StringProtocol where Index == String.Index {
func index(of string: Self, options: String.CompareOptions = []) -> Index? {
return range(of: string, options: options)?.lowerBound
}
func endIndex(of string: Self, options: String.CompareOptions = []) -> Index? {
return range(of: string, options: options)?.upperBound
}
func indexes(of string: Self, options: String.CompareOptions = []) -> [Index] {
var result: [Index] = []
var startIndex = self.startIndex
while startIndex < endIndex,
let range = self[startIndex...].range(of: string, options: options) {
result.append(range.lowerBound)
startIndex = range.lowerBound < range.upperBound ? range.upperBound :
index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
}
return result
}
func ranges(of string: Self, options: String.CompareOptions = []) -> [Range<Index>] {
var result: [Range<Index>] = []
var startIndex = self.startIndex
while startIndex < endIndex,
let range = self[startIndex...].range(of: string, options: options) {
result.append(range)
startIndex = range.lowerBound < range.upperBound ? range.upperBound :
index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
}
return result
}
}
How do I filter an array of Strings to a unique result in Swift
A solution is to use Regular Expression to search for word boundaries
func filterWaypoint(searchString: String, array: [String]) -> String {
let result = array.filter { $0.range(of: "\\b\(searchString)\\b", options: [.regularExpression, .caseInsensitive]) != nil }
print(result)
return result.first ?? ""
}
Remove all non-numeric characters from a string in swift
I was hoping there would be something like stringFromCharactersInSet() which would allow me to specify only valid characters to keep.
You can either use trimmingCharacters
with the inverted
character set to remove characters from the start or the end of the string. In Swift 3 and later:
let result = string.trimmingCharacters(in: CharacterSet(charactersIn: "0123456789.").inverted)
Or, if you want to remove non-numeric characters anywhere in the string (not just the start or end), you can filter
the characters
, e.g. in Swift 4.2.1:
let result = string.filter("0123456789.".contains)
Or, if you want to remove characters from a CharacterSet from anywhere in the string, use:
let result = String(string.unicodeScalars.filter(CharacterSet.whitespaces.inverted.contains))
Or, if you want to only match valid strings of a certain format (e.g. ####.##
), you could use regular expression. For example:
if let range = string.range(of: #"\d+(\.\d*)?"#, options: .regularExpression) {
let result = string[range] // or `String(string[range])` if you need `String`
}
The behavior of these different approaches differ slightly so it just depends on precisely what you're trying to do. Include or exclude the decimal point if you want decimal numbers, or just integers. There are lots of ways to accomplish this.
For older, Swift 2 syntax, see previous revision of this answer.
Related Topics
Autolayout Contraints for a View from Xib
Skphysicsbody Avoid Collision Swift/Spritekit
Does a Mutating Struct Function in Swift Create a New Copy of Self
Firestore Order by Time But Sort by Id
Initialize Lazy Instance Variable with Value That Depends on Other Instance Variables
Why am I Allowed Method Access Less Restrictive Than Class Access
How to Integrate Uiactivityviewcontroller with Swiftui's Scrollview
I Won't Be Able to Return a Value with Alamofire in Swift
Localizewithformat and Variadic Arguments in Swift
How to Create Several Cached Uicolor
How to Track More Than 4 Images at a Time with Arkit
Get Build Date and Time in Swift
How to Get the Height of a Uilabel in Swift
Multiplying Variables and Doubles in Swift
Swift Instance Member Cannot Be Used on Type
Swift Closures Causing Strong Retain Cycle with Self