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

示例:“This is my string”

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

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


当前回答

var str = "This is my string"

print(str.replacingOccurrences(of: " ", with: "+"))

输出是

This+is+my+string

其他回答

斯威夫特4:

let abc = "Hello world"

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

print(result :\(result))

输出:

result : Hello_world

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

下面是Swift 3的示例:

var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
   stringToReplace?.replaceSubrange(range, with: "your")
} 

我认为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"