有什么方法可以替换 Swift String 中的字符吗?

I'm looking for a way to replace characters in a Swift String.

Example: "This is my string"

I'd like to replace with + to get: "This+is+my+string".

How can I achieve this?

转载于:https://stackoverflow.com/questions/24200888/any-way-to-replace-characters-on-swift-string

csdnceshi55
~Onlooker Swift Extension
大约 4 年之前 回复

15个回答

This answer has been updated for Swift 4. 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
})
csdnceshi54
hurriedly% For Swift 3, use let newString = aString.replacingOccurrences(of: " ", with: "+")
接近 4 年之前 回复
csdnceshi60
℡Wang Yan wow, stringByReplacingOccurrencesOfString, how intuitive! I was expecting something like makeNewStringByReplacingOccurrencesOfFirstArgumentByValueInSecondArgument
4 年多之前 回复
csdnceshi77
狐狸.fox I have an alternative solution: stackoverflow.com/a/35463478/756976
4 年多之前 回复
csdnceshi68
local-host For anyone who had issues with using stringByReplacingOccurrencesOfString in Swift 2, you need to import Foundation to be able to use that method.
接近 5 年之前 回复
csdnceshi74
7*4 Nope, trying in a workspace/project. It might be something I'm doing, but thought I'd leave a comment just in case its common.
大约 5 年之前 回复
csdnceshi56
lrony* I'm unable to reproduce that. I'm not sure what's going on with the escaping, and this should be using String's public init(_ characters: String.CharacterView) initializer, which isn't failable. Are you trying this in a playground? I've had playgrounds give me strange output before that didn't match the output from an actually application.
大约 5 年之前 回复
csdnceshi74
7*4 I don't know if I'm doing something wrong but the second swift 2.0 solution leaves me with and optional string. Original String looks like this: "x86_64" and the new mapping looks like "Optional([\"x\", \"8\", \"6\", \"_\", \"6\", \"4\"])"
大约 5 年之前 回复
csdnceshi64
游.程 great swift2 replacement for stringByReplacingOccurrencesOfString
大约 5 年之前 回复
csdnceshi55
~Onlooker options and range parameters are optional
接近 6 年之前 回复

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 4:

let abc = "Hello world"

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

print(result :\(result))

Output:

result : Hello_world

Did you test this :

var test = "This is my string"

let replaced = test.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)

Here is the example for Swift 3:

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

I am using this extension:

extension String {

    func replaceCharacters(characters: String, toSeparator: String) -> String {
        let characterSet = NSCharacterSet(charactersInString: characters)
        let components = self.componentsSeparatedByCharactersInSet(characterSet)
        let result = components.joinWithSeparator("")
        return result
    }

    func wipeCharacters(characters: String) -> String {
        return self.replaceCharacters(characters, toSeparator: "")
    }
}

Usage:

let token = "<34353 43434>"
token.replaceCharacters("< >", toString:"+")
weixin_41568131
10.24 thanks @Ramis it really work fine for me
接近 3 年之前 回复

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.

csdnceshi77
狐狸.fox This is my preferred solution, as it lets you replace multiple characters at once.
3 年多之前 回复

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

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?

Swift 3, Swift 4 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: "+")
csdnceshi77
狐狸.fox this is an answer to this question.
大约 2 年之前 回复
共15条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐