我正在寻找一种方法来取代字符在一个Swift字符串。

示例:“This is my string”

我想用“+”替换“”以获得“This+is+my+string”。

我怎样才能做到这一点呢?


当前回答

斯威夫特5.5

但这在早期版本中可能有效。

我经常替换,因为我想用_或类似的东西替换“任何空白或-”。这个对字符串的扩展让我做到了。

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

用法:

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: "_"))

显然,对于单个字符,. replacingoccurrences (of: " ", with: "+")更好。

我没有做过性能比较

let toArray = aString.components(separatedBy: characterSet)
let backToString = toArray.joined(separator: "+") 

风格做在Ramis的扩展。如果有人愿意,我会很感兴趣的。

参见替换表情符号:https://stackoverflow.com/a/63416058/5946596

其他回答

迅速扩展:

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
    }

}

继续使用let replacedString = yorString。stringbyreplacement (replaceStrings: [" ","?","."],加上:“+”)

函数的速度是我几乎不能感到骄傲的,但是你可以在一次传递一个String数组来进行多次替换。

修改现有可变字符串的类别:

extension String
{
    mutating func replace(originalString:String, withString newString:String)
    {
        let replacedString = self.stringByReplacingOccurrencesOfString(originalString, withString: newString, options: nil, range: nil)
        self = replacedString
    }
}

使用:

name.replace(" ", withString: "+")

你可以用这个:

let s = "This is my string"
let modified = s.replace(" ", withString:"+")    

如果你在你的代码中添加这个扩展方法:

extension String
{
    func replace(target: String, withString: String) -> String
    {
       return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
    }
}

斯威夫特3:

extension String
{
    func replace(target: String, withString: String) -> String
    {
        return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
    }
}

这是一个在字符串上的替换方法的扩展,它没有不必要的复制,并在适当的地方做所有事情:

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

(方法签名也模仿内置String.replacingOccurrences()方法的签名)

可用于以下方式:

var string = "this is a string"
string.replaceOccurrences(of: " ", with: "_")
print(string) // "this_is_a_string"

斯威夫特4:

let abc = "Hello world"

let result = abc.replacingOccurrences(of: " ", with: "_", 
    options: NSString.CompareOptions.literal, range:nil)

print(result :\(result))

输出:

result : Hello_world