Any way to replace characters on Swift String?

2018-12-31 08:59发布

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?

标签: ios swift string
15条回答
荒废的爱情
2楼-- · 2018-12-31 09:32

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
查看更多
不流泪的眼
3楼-- · 2018-12-31 09:32

Here is the example for Swift 3:

var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
   stringToReplace?.replaceSubrange(range, with: "your")
} 
查看更多
笑指拈花
4楼-- · 2018-12-31 09:33

I think Regex is the most flexible and solid way:

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"
查看更多
无色无味的生活
5楼-- · 2018-12-31 09:35

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.

查看更多
人气声优
6楼-- · 2018-12-31 09:36

Here's an extension for an in-place occurrences replace method on String, that doesn't no an unnecessary copy and do everything in place:

extension String {
    mutating func replaceOccurrences(of target: String, with replacement: String, options: String.CompareOptions = [], locale: Locale? = nil) {
        var range: Range<String.Index>?
        repeat {
            range = self.range(of: source, options: options, range: range.map { $0.lowerBound..<self.endIndex }, locale: locale)
            if let range = range {
                self.replaceSubrange(range, with: new)
            }
        } while range != nil
    }
}

(The method signature also mimics the signature of the built-in String.replacingOccurrences() method)

May be used in the following way:

var string = "this is a string"
string.replaceOccurrences(of: " ", with: "_")
print(string) // "this_is_a_string"
查看更多
美炸的是我
7楼-- · 2018-12-31 09:36

I've implemented this very easy func:

func convap (text : String) -> String {
    return text.stringByReplacingOccurrencesOfString("'", withString: "''")
}

So you can write:

let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')
查看更多
登录 后发表回答