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

示例:“This is my string”

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

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


当前回答

我认为Regex是最灵活和可靠的方法:

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 2开始,String不再符合SequenceType。换句话说,你不能用for…在循环。

简单而简单的方法是将String转换为Array以获得索引的好处:

let input = Array(str)

我记得当我试图索引到字符串不使用任何转换。我真的很沮丧,因为我不能想出或达到一个理想的结果,我准备放弃了。 但我最终创建了我自己的解决方案,这里是扩展的完整代码:

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

现在,你可以像你最初想要的那样,使用索引从字符串中读取和替换单个字符:

var str = "cat"
for i in 0..<str.count {
 if str[i] == "c" {
   str[i] = "h"
 }
}

print(str)

这是一种简单而有用的方式来使用它,并通过Swift的字符串访问模型。 现在,下次你会觉得它很顺利,因为你可以循环字符串,而不是将它强制转换到数组中。

尝试一下,看看它是否有帮助!

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

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"

Swift 3, Swift 4, Swift 5解决方案

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

你可以用这个:

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

基于Ramis回答的Swift 3解决方案:

extension String {
    func withReplacedCharacters(_ characters: String, by separator: String) -> String {
        let characterSet = CharacterSet(charactersIn: characters)
        return components(separatedBy: characterSet).joined(separator: separator)
    }
}

尝试根据Swift 3的命名约定,提出一个合适的函数名。