【发布时间】:2014-06-13 08:28:39
【问题描述】:
我正在寻找一种方法来替换 Swift String 中的字符。
示例:“这是我的字符串”
我想把“”换成“+”得到“This+is+my+string”。
我怎样才能做到这一点?
【问题讨论】:
我正在寻找一种方法来替换 Swift String 中的字符。
示例:“这是我的字符串”
我想把“”换成“+”得到“This+is+my+string”。
我怎样才能做到这一点?
【问题讨论】:
此答案已针对 Swift 4 和 5 进行了更新。如果您仍在使用 Swift 1、2 或 3,请查看修订历史记录。
您有几个选择。您可以使用as @jaumard suggested 并使用replacingOccurrences()
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)
正如下面@cprcrack 所指出的,options 和range 参数是可选的,因此如果您不想指定字符串比较选项或在其中进行替换的范围,您只需要以下内容。
let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+")
或者,如果数据是这样的特定格式,您只是替换分隔字符,您可以使用components() 将字符串分解为数组,然后您可以使用join() 函数将它们与指定的分隔符重新组合在一起。
let toArray = aString.components(separatedBy: " ")
let backToString = toArray.joined(separator: "+")
或者,如果您正在寻找不使用 NSString 的 API 的更 Swifty 解决方案,您可以使用它。
let aString = "Some search text"
let replaced = String(aString.map {
$0 == " " ? "+" : $0
})
【讨论】:
"x86_64",新的映射看起来像 "Optional([\"x\", \"8\", \"6\", \"_\", \"6\", \"4\"])"
stringByReplacingOccurrencesOfString 时遇到问题的任何人,您需要 import Foundation 才能使用该方法。
你可以用这个:
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、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: "+")
【讨论】:
你测试了吗:
var test = "This is my string"
let replaced = test.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)
【讨论】:
我正在使用这个扩展:
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: "")
}
}
用法:
let token = "<34353 43434>"
token.replaceCharacters("< >", toString:"+")
【讨论】:
斯威夫特 4:
let abc = "Hello world"
let result = abc.replacingOccurrences(of: " ", with: "_",
options: NSString.CompareOptions.literal, range:nil)
print(result :\(result))
输出:
result : Hello_world
【讨论】:
一个类似于 Sunkas 的 Swift 3 解决方案:
extension String {
mutating func replace(_ originalString:String, with newString:String) {
self = self.replacingOccurrences(of: originalString, with: newString)
}
}
用途:
var string = "foo!"
string.replace("!", with: "?")
print(string)
输出:
foo?
【讨论】:
var str = "This is my string"
print(str.replacingOccurrences(of: " ", with: "+"))
输出是
This+is+my+string
【讨论】:
修改现有可变字符串的类别:
extension String
{
mutating func replace(originalString:String, withString newString:String)
{
let replacedString = self.stringByReplacingOccurrencesOfString(originalString, withString: newString, options: nil, range: nil)
self = replacedString
}
}
用途:
name.replace(" ", withString: "+")
【讨论】:
基于Ramis' answer的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 命名约定想出一个合适的函数名。
【讨论】:
发生在我身上的事情较少,我只是想在String中更改(一个单词或一个字符)
所以我使用了Dictionary
extension String{
func replace(_ dictionary: [String: String]) -> String{
var result = String()
var i = -1
for (of , with): (String, String)in dictionary{
i += 1
if i<1{
result = self.replacingOccurrences(of: of, with: with)
}else{
result = result.replacingOccurrences(of: of, with: with)
}
}
return result
}
}
用法
let mobile = "+1 (800) 444-9999"
let dictionary = ["+": "00", " ": "", "(": "", ")": "", "-": ""]
let mobileResult = mobile.replace(dictionary)
print(mobileResult) // 001800444999
【讨论】:
replace
var str = "This is my string"
str = str.replacingOccurrences(of: " ", with: "+")
print(str)
【讨论】:
String 中找不到replacingOccurrences?
Xcode 11 • Swift 5.1
StringProtocolreplacingOccurrences的mutating方法可以实现如下:
extension RangeReplaceableCollection where Self: StringProtocol {
mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<String.Index>? = nil) {
self = .init(replacingOccurrences(of: target, with: replacement, options: options, range: searchRange))
}
}
var name = "This is my string"
name.replaceOccurrences(of: " ", with: "+")
print(name) // "This+is+my+string\n"
【讨论】:
我认为 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 扩展:
extension String {
func stringByReplacing(replaceStrings set: [String], with: String) -> String {
var stringObject = self
for string in set {
stringObject = self.stringByReplacingOccurrencesOfString(string, withString: with)
}
return stringObject
}
}
继续像let replacedString = yorString.stringByReplacing(replaceStrings: [" ","?","."], with: "+")一样使用它
函数的速度是我几乎不能骄傲的事情,但你可以一次传递String 的数组来进行多次替换。
【讨论】:
这是 Swift 3 的示例:
var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
stringToReplace?.replaceSubrange(range, with: "your")
}
【讨论】:
这在 swift 4.2 中很容易。只需使用replacingOccurrences(of: " ", with: "_") 替换
var myStr = "This is my string"
let replaced = myStr.replacingOccurrences(of: " ", with: "_")
print(replaced)
【讨论】:
如果你不想使用 Objective-C 的 NSString 方法,你可以使用 split 和 join:
var string = "This is my string"
string = join("+", split(string, isSeparator: { $0 == " " }))
split(string, isSeparator: { $0 == " " }) 返回一个字符串数组 (["This", "is", "my", "string"])。
join 将这些元素与+ 连接起来,得到所需的输出:"This+is+my+string"。
【讨论】:
我已经实现了这个非常简单的函数:
func convap (text : String) -> String {
return text.stringByReplacingOccurrencesOfString("'", withString: "''")
}
所以你可以写:
let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')
【讨论】:
你可以测试一下:
让 newString = test.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)
【讨论】:
从 Swift 2 开始,String 不再符合 SequenceType。换句话说,您不能使用 for...in 循环遍历字符串。
简单易行的方法是将String 转换为Array 即可获得索引的好处,就像这样:
let input = Array(str)
我记得当我尝试在不使用任何转换的情况下对String 进行索引时。我真的很沮丧,因为我无法想出或达到预期的结果,并且即将放弃。
但我最终创建了自己的解决方案,这是扩展的完整代码:
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 的 String 访问模型是一种简单而有用的方式。
现在你会觉得下次你可以按原样循环遍历字符串,而不是把它转换成Array。
试一试,看看是否有帮助!
【讨论】:
这是String 上的就地匹配替换方法的扩展,它没有不必要的复制,并且一切都在原地完成:
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"
【讨论】: