有什么办法取代字符在Swift字符串?

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

示例:“This is my string”

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

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

484100 次浏览

你测试过这个吗?

var test = "This is my string"


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

这个答案是更新为Swift 4 &5。如果你还在使用Swift 1、2或3,请参阅修订历史

你有两个选择。您可以执行正如@jaumard所建议的和使用replacingOccurrences()

let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)

正如下面@cprcrack所指出的,optionsrange参数是可选的,所以如果您不想指定字符串比较选项或替换范围,您只需要以下内容。

let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+")

或者,如果数据是这样的特定格式(您只是替换分隔符),则可以使用components()将字符串拆分为一个数组,然后可以使用join()函数将它们与指定的分隔符组合在一起。

let toArray = aString.components(separatedBy: " ")
let backToString = toArray.joined(separator: "+")

或者如果你正在寻找一个更Swifty的解决方案,不利用NSString的API,你可以使用这个。

let aString = "Some search text"


let replaced = String(aString.map {
$0 == " " ? "+" : $0
})

你可以用这个:

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

修改现有可变字符串的类别:

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

如果你不想使用objective - c# EYZ0方法,你可以只使用splitjoin:

var string = "This is my string"
string = join("+", split(string, isSeparator: { $0 == " " }))

返回一个字符串数组(["This", "is", "my", "string"])。

join将这些元素与+连接起来,产生所需的输出:"This+is+my+string"

斯威夫特5.5

我正在使用这个扩展:

extension String {


func replaceCharacters(characters: String, toSeparator: String) -> String {
let characterSet = CharacterSet(charactersIn: characters)
let components = components(separatedBy: characterSet)
let result = components.joined(separator: toSeparator)
return result
}


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

用法:

"<34353 43434>".replaceCharacters(characters: "< >", toSeparator:"+") // +34353+43434+
"<34353 43434>".wipeCharacters(characters: "< >") // 3435343434

我实现了这个非常简单的func:

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

所以你可以这样写:

let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')

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

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

迅速扩展:

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

一个快速的解决方案沿着Sunkas的路线:

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?

基于。拉米斯的回答的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上的替换方法的扩展,它没有不必要的复制,并在适当的地方做所有事情:

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"

斯威夫特4:

let abc = "Hello world"


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


print(result :\(result))

输出:

result : Hello_world

这在swift 4.2中很容易做到。只需使用replacingOccurrences(of: " ", with: "_")替换即可

var myStr = "This is my string"
let replaced = myStr.replacingOccurrences(of: " ", with: "_")
print(replaced)

在我身上发生的事情很少,我只是想改变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

Xcode 11•Swift 5.1

StringProtocol replacingOccurrences的变异方法实现如下:

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"

你可以测试这个:

let newString = test。stringByReplacingOccurrencesOfString(" ", withString: "+",选项:nil,范围:nil)

var str = "This is my string"
str = str.replacingOccurrences(of: " ", with: "+")
print(str)
var str = "This is my string"


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

输出是

This+is+my+string

从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的字符串访问模型。 现在你会觉得它是一帆风顺的下一次,当你可以循环字符串,就像它是,而不是强制转换到Array.

尝试一下,看看它是否有帮助!