To keep only alphabets in a string in Swift, you can use regular expressions from the 'Foundation' framework to remove non-alphabetic characters.
In this example,
str1
with a value of "Hello123 World"
.[^a-zA-Z]
to match non-alphabetic characters.replacingOccurrences
method with the regular expression pattern to replace all non-alphabetic characters with an empty string.str1
.import Foundation
var str1 = "Hello123 World"
let pattern = "[^a-zA-Z]"
let reg = try! NSRegularExpression(pattern: pattern)
str1 = reg.stringByReplacingMatches(in: str1, options: [], range: NSRange(location: 0, length: str1.utf16.count), withTemplate: "")
print("Modified string: \(str1)")
Modified string: HelloWorld
In this example,
str2
with a value of "apple@banana"
.[^a-zA-Z]
to match non-alphabetic characters.replacingOccurrences
method with the regular expression pattern to replace all non-alphabetic characters with an empty string.str2
.import Foundation
var str2 = "apple@banana"
let pattern = "[^a-zA-Z]"
let reg = try! NSRegularExpression(pattern: pattern)
str2 = reg.stringByReplacingMatches(in: str2, options: [], range: NSRange(location: 0, length: str2.utf16.count), withTemplate: "")
print("Modified string: \(str2)")
Modified string: applebanana
In this tutorial, we learned How to keep only Alphabets in a String in Swift language with well detailed examples.