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

示例:“This is my string”

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

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


当前回答

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

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

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

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"

你可以用这个:

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

你可以测试这个:

let newString = test。stringByReplacingOccurrencesOfString(" ", withString: "+",选项:nil,范围:nil)

Swift 4和5已经更新了这个答案。如果你还在使用Swift 1、2或3,请查看修订历史。

你有两个选择。你可以像@jaumard建议的那样,使用replacingOccurrences()

let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)

正如下面@cprcrack所指出的,选项和范围参数是可选的,所以如果您不想指定字符串比较选项或执行替换的范围,您只需要以下内容。

let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+")

或者,如果数据是这样的特定格式,其中只是替换分隔符,则可以使用components()将字符串拆分为一个数组,然后可以使用join()函数将它们与指定的分隔符组合在一起。

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

或者如果你正在寻找一个更Swifty的解决方案,不利用NSString的API,你可以使用这个。

let aString = "Some search text"

let replaced = String(aString.map {
    $0 == " " ? "+" : $0
})