let firstSet = CharacterSet(charactersIn: "-()")
let secondSet = CharacterSet.whitespaces
I need to replace +48 (23) 899899 098 with +4823899899098.
let output = "+48 (23) 899899 098".components(separatedBy: firstSet).joined(separator: "")
but here I need to use two CharacterSets. How can I join them into one?
You can use union(_:) for that.
let output = "+48 (23) 899899 098".components(separatedBy: firstSet.union(secondSet)).joined()
Alternatively use regular expression:
let output = "+48 (23) 899899 098"
let trimmedOutput = output.replacingOccurrences(of: "[^0-9+]", with: "", options: .regularExpression)
// -> +4823899899098"
you can use function for phone formatting, so it would be reusable through app
//removes "(", ")", "-", " " etc. and adds "+" for region code format
extension String {
func phoneToString() -> String {
var value = "+"
for character in self.characters {
if Int(String(character)) != nil {
value = value + String(character)
}
}
return value
}
}
let phoneWithoutSpaces = "+48 (23) 899899 098".phoneToString()
I have a long string in swift3 and want to check if it contains word1 and word2. It could also be more than 2 search words. I found out following solution:
var Text = "Hello Swift-world"
var TextArray = ["Hello", "world"]
var count = 0
for n in 0..<TextArray.count {
if (Text.contains(TextArray[n])) {
count += 1
}
}
if (count == TextArray.count) {
print ("success")
}
But this seems very complicated, is there not an easier way to solve this? (Xcode8 and swift3)
If you are looking for less code:
let text = "Hello Swift-world"
let wordList = ["Hello", "world"]
let success = !wordList.contains(where: { !text.contains($0) })
print(success)
It is also a little more efficient than your solution because
the contains method returns as soon as a "not contained" word
is found.
As of Swift 4 or later, you can use allSatisfy:
let success = wordList.allSatisfy(text.contains)
A more Swifty solution that will stop searching after it found a non-existent word:
var text = "Hello Swift-world"
var textArray = ["Hello", "world"]
let match = textArray.reduce(true) { !$0 ? false : (text.range(of: $1) != nil ) }
Another way to do it which stops after it found a non-match:
let match = textArray.first(where: { !text.contains($0) }) == nil
Another possibility is regular expressions:
// *'s are wildcards
let regexp = "(?=.*Hello*)(?=.*world*)"
if let range = Text.range(of:regexp, options: .regularExpression) {
print("this string contains Hello world")
} else {
print("this string doesn't have the words we want")
}
Every example of trimming strings in Swift remove both leading and trailing whitespace, but how can only trailing whitespace be removed?
For example, if I have a string:
" example "
How can I end up with:
" example"
Every solution I've found shows trimmingCharacters(in: CharacterSet.whitespaces), but I want to retain the leading whitespace.
RegEx is a possibility, or a range can be derived to determine index of characters to remove, but I can't seem to find an elegant solution for this.
With regular expressions:
let string = " example "
let trimmed = string.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression)
print(">" + trimmed + "<")
// > example<
\s+ matches one or more whitespace characters, and $ matches
the end of the string.
In Swift 4 & Swift 5
This code will also remove trailing new lines.
It works based on a Character struct's method .isWhitespace
var trailingSpacesTrimmed: String {
var newString = self
while newString.last?.isWhitespace == true {
newString = String(newString.dropLast())
}
return newString
}
This short Swift 3 extension of string uses the .anchored and .backwards option of rangeOfCharacter and then calls itself recursively if it needs to loop. Because the compiler is expecting a CharacterSet as the parameter, you can just supply the static when calling, e.g. "1234 ".trailing(.whitespaces) will return "1234". (I've not done timings, but would expect faster than regex.)
extension String {
func trailingTrim(_ characterSet : CharacterSet) -> String {
if let range = rangeOfCharacter(from: characterSet, options: [.anchored, .backwards]) {
return self.substring(to: range.lowerBound).trailingTrim(characterSet)
}
return self
}
}
In Foundation you can get ranges of indices matching a regular expression. You can also replace subranges. Combining this, we get:
import Foundation
extension String {
func trimTrailingWhitespace() -> String {
if let trailingWs = self.range(of: "\\s+$", options: .regularExpression) {
return self.replacingCharacters(in: trailingWs, with: "")
} else {
return self
}
}
}
You can also have a mutating version of this:
import Foundation
extension String {
mutating func trimTrailingWhitespace() {
if let trailingWs = self.range(of: "\\s+$", options: .regularExpression) {
self.replaceSubrange(trailingWs, with: "")
}
}
}
If we match against \s* (as Martin R. did at first) we can skip the if let guard and force-unwrap the optional since there will always be a match. I think this is nicer since it's obviously safe, and remains safe if you change the regexp. I did not think about performance.
Handy String extension In Swift 4
extension String {
func trimmingTrailingSpaces() -> String {
var t = self
while t.hasSuffix(" ") {
t = "" + t.dropLast()
}
return t
}
mutating func trimmedTrailingSpaces() {
self = self.trimmingTrailingSpaces()
}
}
Swift 4
extension String {
var trimmingTrailingSpaces: String {
if let range = rangeOfCharacter(from: .whitespacesAndNewlines, options: [.anchored, .backwards]) {
return String(self[..<range.lowerBound]).trimmingTrailingSpaces
}
return self
}
}
Demosthese's answer is a useful solution to the problem, but it's not particularly efficient. This is an upgrade to their answer, extending StringProtocol instead, and utilizing Substring to remove the need for repeated copying.
extension StringProtocol {
#inline(__always)
var trailingSpacesTrimmed: Self.SubSequence {
var view = self[...]
while view.last?.isWhitespace == true {
view = view.dropLast()
}
return view
}
}
No need to create a new string when dropping from the end each time.
extension String {
func trimRight() -> String {
String(reversed().drop { $0.isWhitespace }.reversed())
}
}
This operates on the collection and only converts the result back into a string once.
It's a little bit hacky :D
let message = " example "
var trimmed = ("s" + message).trimmingCharacters(in: .whitespacesAndNewlines)
trimmed = trimmed.substring(from: trimmed.index(after: trimmed.startIndex))
Without regular expression there is not direct way to achieve that.Alternatively you can use the below function to achieve your required result :
func removeTrailingSpaces(with spaces : String) -> String{
var spaceCount = 0
for characters in spaces.characters{
if characters == " "{
print("Space Encountered")
spaceCount = spaceCount + 1
}else{
break;
}
}
var finalString = ""
let duplicateString = spaces.replacingOccurrences(of: " ", with: "")
while spaceCount != 0 {
finalString = finalString + " "
spaceCount = spaceCount - 1
}
return (finalString + duplicateString)
}
You can use this function by following way :-
let str = " Himanshu "
print(removeTrailingSpaces(with : str))
One line solution with Swift 4 & 5
As a beginner in Swift and iOS programming I really like #demosthese's solution above with the while loop as it's very easy to understand. However the example code seems longer than necessary. The following uses essentially the same logic but implements it as a single line while loop.
// Remove trailing spaces from myString
while myString.last == " " { myString = String(myString.dropLast()) }
This can also be written using the .isWhitespace property, as in #demosthese's solution, as follows:
while myString.last?.isWhitespace == true { myString = String(myString.dropLast()) }
This has the benefit (or disadvantage, depending on your point of view) that this removes all types of whitespace, not just spaces but (according to Apple docs) also including newlines, and specifically the following characters:
“\t” (U+0009 CHARACTER TABULATION)
“ “ (U+0020 SPACE)
U+2029 PARAGRAPH SEPARATOR
U+3000 IDEOGRAPHIC SPACE
Note: Even though .isWhitespace is a Boolean it can't be used directly in the while loop as it ends up being optional ? due to the chaining of the optional .last property, which returns nil if the String (or collection) is empty. The == true logic gets around this since nil != true.
I'd love to get some feedback on this, esp. in case anyone sees any issues or drawbacks with this simple single line approach.
Swift 5
extension String {
func trimTrailingWhiteSpace() -> String {
guard self.last == " " else { return self }
var tmp = self
repeat {
tmp = String(tmp.dropLast())
} while tmp.last == " "
return tmp
}
}
I have a block that updates the view for each String. In its object class I pass it by:
func eachFeaturesSection(block: ((String?) -> Void)?) {
propertyFeatures.forEach { feature in
guard let feature = feature as? RealmString else {
return
}
let features = feature.stringValue
block?(features)
}
}
and I will get it in ViewController, by:
listing!.eachFeaturesSection({ (features) in
print(features)
self.facilities = features!
})
So it will print as:
Optional("String 1")
Optional("String 2")
and self.facilities will be set to latest value which is self.facilities = "String 2"
cell.features.text = features // it will print String 2
So, how can I achieve to join all strings together in one string such as self.facilities = "String 1, String 2". I used .jointString does not work. Thank you for any help.
Maybe you could add them to an array of String elements and then, when done, call joined on that array.
So something like this in your ViewController:
var featuresArray = [String]()
listing!.eachFeaturesSectionT({ (features) in
print(features)
featuresArray.append(features!)
})
//Swift 3 syntax
cell.features.text = featuresArray.joined(separator: ", ")
//Swift 2 syntax
cell.features.text = featuresArray.joinWithSeparator(", ")
Hope that helps you.
self.facilities = features! is doing nothing but keeps updating the value every iteration
Change the line self.facilities = features! to self.facilities += features! or self.facilities = self.facilities + ", " + features!
Here's how I'd do it (assuming your propertyFeatures is an array of RealmString):
Swift 3:
let string = (propertyFeatures.map { $0.stringValue }).joined(separator: ", ")
Swift 2:
let string = (propertyFeatures.map { $0.stringValue }).joinWithSeparator(", ")
I am looking for a way to replace characters in a Swift String.
Example: "This is my string"
I would like to replace " " with "+" to get "This+is+my+string".
How can I achieve this?
This answer has been updated for Swift 4 & 5. If you're still using Swift 1, 2 or 3 see the revision history.
You have a couple of options. You can do as #jaumard suggested and use replacingOccurrences()
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)
And as noted by #cprcrack below, the options and range parameters are optional, so if you don't want to specify string comparison options or a range to do the replacement within, you only need the following.
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+")
Or, if the data is in a specific format like this, where you're just replacing separation characters, you can use components() to break the string into and array, and then you can use the join() function to put them back to together with a specified separator.
let toArray = aString.components(separatedBy: " ")
let backToString = toArray.joined(separator: "+")
Or if you're looking for a more Swifty solution that doesn't utilize API from NSString, you could use this.
let aString = "Some search text"
let replaced = String(aString.map {
$0 == " " ? "+" : $0
})
You can use this:
let s = "This is my string"
let modified = s.replace(" ", withString:"+")
If you add this extension method anywhere in your code:
extension String
{
func replace(target: String, withString: String) -> String
{
return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
}
}
Swift 3:
extension String
{
func replace(target: String, withString: String) -> String
{
return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
}
}
Swift 3, Swift 4, Swift 5 Solution
let exampleString = "Example string"
//Solution suggested above in Swift 3.0
let stringToArray = exampleString.components(separatedBy: " ")
let stringFromArray = stringToArray.joined(separator: "+")
//Swiftiest solution
let swiftyString = exampleString.replacingOccurrences(of: " ", with: "+")
Did you test this :
var test = "This is my string"
let replaced = test.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)
var str = "This is my string"
print(str.replacingOccurrences(of: " ", with: "+"))
Output is
This+is+my+string
Swift 5.5
I am using this extension:
extension String {
func replaceCharacters(characters: String, toSeparator: String) -> String {
let characterSet = CharacterSet(charactersIn: characters)
let components = components(separatedBy: characterSet)
let result = components.joined(separator: toSeparator)
return result
}
func wipeCharacters(characters: String) -> String {
return self.replaceCharacters(characters: characters, toSeparator: "")
}
}
Usage:
"<34353 43434>".replaceCharacters(characters: "< >", toSeparator:"+") // +34353+43434+
"<34353 43434>".wipeCharacters(characters: "< >") // 3435343434
Swift 4:
let abc = "Hello world"
let result = abc.replacingOccurrences(of: " ", with: "_",
options: NSString.CompareOptions.literal, range:nil)
print(result :\(result))
Output:
result : Hello_world
A Swift 3 solution along the lines of Sunkas's:
extension String {
mutating func replace(_ originalString:String, with newString:String) {
self = self.replacingOccurrences(of: originalString, with: newString)
}
}
Use:
var string = "foo!"
string.replace("!", with: "?")
print(string)
Output:
foo?
A category that modifies an existing mutable String:
extension String
{
mutating func replace(originalString:String, withString newString:String)
{
let replacedString = self.stringByReplacingOccurrencesOfString(originalString, withString: newString, options: nil, range: nil)
self = replacedString
}
}
Use:
name.replace(" ", withString: "+")
Swift 3 solution based on Ramis' answer:
extension String {
func withReplacedCharacters(_ characters: String, by separator: String) -> String {
let characterSet = CharacterSet(charactersIn: characters)
return components(separatedBy: characterSet).joined(separator: separator)
}
}
Tried to come up with an appropriate function name according to Swift 3 naming convention.
Less happened to me, I just want to change (a word or character) in the String
So I've use the Dictionary
extension String{
func replace(_ dictionary: [String: String]) -> String{
var result = String()
var i = -1
for (of , with): (String, String)in dictionary{
i += 1
if i<1{
result = self.replacingOccurrences(of: of, with: with)
}else{
result = result.replacingOccurrences(of: of, with: with)
}
}
return result
}
}
usage
let mobile = "+1 (800) 444-9999"
let dictionary = ["+": "00", " ": "", "(": "", ")": "", "-": ""]
let mobileResult = mobile.replace(dictionary)
print(mobileResult) // 001800444999
Xcode 11 • Swift 5.1
The mutating method of StringProtocol replacingOccurrences can be implemented as follow:
extension RangeReplaceableCollection where Self: StringProtocol {
mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<String.Index>? = nil) {
self = .init(replacingOccurrences(of: target, with: replacement, options: options, range: searchRange))
}
}
var name = "This is my string"
name.replaceOccurrences(of: " ", with: "+")
print(name) // "This+is+my+string\n"
var str = "This is my string"
str = str.replacingOccurrences(of: " ", with: "+")
print(str)
This is easy in swift 4.2. just use replacingOccurrences(of: " ", with: "_") for replace
var myStr = "This is my string"
let replaced = myStr.replacingOccurrences(of: " ", with: "_")
print(replaced)
Since Swift 2, String does no longer conform to SequenceType. In other words, you can not iterate through a string with a for...in loop.
The simple and easy way is to convert String to Array to get the benefit of the index just like that:
let input = Array(str)
I remember when I tried to index into String without using any conversion. I was really frustrated that I couldn’t come up with or reach a desired result, and was about to give up.
But I ended up creating my own workaround solution, and here is the full code of the extension:
extension String {
subscript (_ index: Int) -> String {
get {
String(self[self.index(startIndex, offsetBy: index)])
}
set {
remove(at: self.index(self.startIndex, offsetBy: index))
insert(Character(newValue), at: self.index(self.startIndex, offsetBy: index))
}
}
}
Now that you can read and replace a single character from string using its index just like you originally wanted to:
var str = "cat"
for i in 0..<str.count {
if str[i] == "c" {
str[i] = "h"
}
}
print(str)
It’s simple and useful way to use it and get through Swift’s String access model.
Now that you’ll feel it’s smooth sailing next time when you can loop through the string just as it is, not casting it into Array.
Try it out, and see if it can help!
I've implemented this very simple func:
func convap (text : String) -> String {
return text.stringByReplacingOccurrencesOfString("'", withString: "''")
}
So you can write:
let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')
I think Regex is the most flexible and solid way:
var str = "This is my string"
let regex = try! NSRegularExpression(pattern: " ", options: [])
let output = regex.stringByReplacingMatchesInString(
str,
options: [],
range: NSRange(location: 0, length: str.characters.count),
withTemplate: "+"
)
// output: "This+is+my+string"
Swift extension:
extension String {
func stringByReplacing(replaceStrings set: [String], with: String) -> String {
var stringObject = self
for string in set {
stringObject = self.stringByReplacingOccurrencesOfString(string, withString: with)
}
return stringObject
}
}
Go on and use it like let replacedString = yorString.stringByReplacing(replaceStrings: [" ","?","."], with: "+")
The speed of the function is something that i can hardly be proud of, but you can pass an array of String in one pass to make more than one replacement.
Here is the example for Swift 3:
var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
stringToReplace?.replaceSubrange(range, with: "your")
}
Here's an extension for an in-place occurrences replace method on String, that doesn't no an unnecessary copy and do everything in place:
extension String {
mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], locale: Locale? = nil) {
var range: Range<Index>?
repeat {
range = self.range(of: target, options: options, range: range.map { self.index($0.lowerBound, offsetBy: replacement.count)..<self.endIndex }, locale: locale)
if let range = range {
self.replaceSubrange(range, with: replacement)
}
} while range != nil
}
}
(The method signature also mimics the signature of the built-in String.replacingOccurrences() method)
May be used in the following way:
var string = "this is a string"
string.replaceOccurrences(of: " ", with: "_")
print(string) // "this_is_a_string"
If you don't want to use the Objective-C NSString methods, you can just use split and join:
var string = "This is my string"
string = join("+", split(string, isSeparator: { $0 == " " }))
split(string, isSeparator: { $0 == " " }) returns an array of strings (["This", "is", "my", "string"]).
join joins these elements with a +, resulting in the desired output: "This+is+my+string".
you can test this:
let newString = test.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)
Swift 5.5
But this might work in earlier versions.
I'm frequently replacing because I want to replace "any whitespace or -" with a _ or something like that. This extension on string lets me do that.
extension String {
func removingCharacters(_ characters:CharacterSet) -> Self {
Self(self.unicodeScalars.filter {
!characters.contains($0)
})
}
func removingCharacters(in string:String) -> Self {
Self(self.unicodeScalars.filter {
!CharacterSet(charactersIn:string).contains($0)
})
}
func replacingCharacters(_ characters:CharacterSet, with newChar:Character) -> Self {
String(self.compactMap( {
CharacterSet(charactersIn: "\($0.1)").isSubset(of: characters)
? newChar : $0.1
}))
}
func replacingCharacters(in string:String, with newChar:Character) -> Self {
String(self.compactMap( {
CharacterSet(charactersIn: "\($0)").isSubset(of: CharacterSet(charactersIn:string))
? newChar : $0
}))
}
}
usage:
print("hello \n my name\t is Joe".removingCharacters(.whitespacesAndNewlines))
print("hello \n my name\t is Joe".removingCharacters(in: " \t\n"))
print("ban annan anann ana".replacingCharacters(.whitespacesAndNewlines, with: "_"))
print("ban-annan anann ana".replacingCharacters(in: " -", with: "_"))
Obviously for a single character the .replacingOccurrences(of: " ", with: "+") is better.
I have not done a performance comparison to the
let toArray = aString.components(separatedBy: characterSet)
let backToString = toArray.joined(separator: "+")
style done in Ramis's extension. I'd be interested if someone does.
See also replacing emoji's: https://stackoverflow.com/a/63416058/5946596