有什么方法可以替换 Swift String 上的字符? [英] Any way to replace characters on Swift String?

查看:18
本文介绍了有什么方法可以替换 Swift String 上的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来替换 Swift String 中的字符.

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

示例:这是我的字符串"

Example: "This is my string"

我想用+"替换"以获得This+is+my+string".

I would like to replace " " with "+" to get "This+is+my+string".

我怎样才能做到这一点?

How can I achieve this?

推荐答案

此答案已针对 Swift 4 和更新.5.如果您仍在使用 Swift 1、2 或 3,请查看修订历史.

This answer has been updated for Swift 4 & 5. If you're still using Swift 1, 2 or 3 see the revision history.

您有几个选择.你可以按照@jaumard的建议并使用replacingOccurrences()

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)

正如下面@cprcrack 所指出的,optionsrange 参数是可选的,因此如果您不想指定字符串比较选项或要执行的范围里面的替换,你只需要以下.

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

或者,如果数据是这样的特定格式,你只是替换分隔符,你可以使用components()将字符串分解成数组,然后你就可以使用 join() 函数将它们与指定的分隔符重新组合在一起.

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

或者,如果您正在寻找不使用来自 NSString 的 API 的更 Swifty 解决方案,您可以使用它.

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

这篇关于有什么方法可以替换 Swift String 上的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆