我正在寻找一种方法来取代字符在一个Swift字符串。

示例:“This is my string”

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

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


你测试过这个吗?

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所指出的,选项和范围参数是可选的,所以如果您不想指定字符串比较选项或执行替换的范围,您只需要以下内容。

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 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"。


斯威夫特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。stringbyreplacement (replaceStrings: [" ","?","."],加上:“+”)

函数的速度是我几乎不能感到骄傲的,但是你可以在一次传递一个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)
    }
}

Use:

var string = "foo!"
string.replace("!", with: "?")
print(string)

输出:

foo?

基于Ramis回答的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的命名约定,提出一个合适的函数名。


这是一个在字符串上的替换方法的扩展,它没有不必要的复制,并在适当的地方做所有事情:

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)

很少发生在我身上,我只是想改变字符串中的(一个单词或字符)

所以我用了字典

  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…在循环。

简单而简单的方法是将String转换为Array以获得索引的好处:

let input = Array(str)

我记得当我试图索引到字符串不使用任何转换。我真的很沮丧,因为我不能想出或达到一个理想的结果,我准备放弃了。 但我最终创建了我自己的解决方案,这里是扩展的完整代码:

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的字符串访问模型。 现在,下次你会觉得它很顺利,因为你可以循环字符串,而不是将它强制转换到数组中。

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


斯威夫特5.5

但这在早期版本中可能有效。

我经常替换,因为我想用_或类似的东西替换“任何空白或-”。这个对字符串的扩展让我做到了。

extension String {
    func removingCharacters(_ characters:CharacterSet) -> Self {
        Self(self.unicodeScalars.filter {
            !characters.contains($0)
        })
    }
    func removingCharacters(in string:String) -> Self {
        Self(self.unicodeScalars.filter {
            !CharacterSet(charactersIn:string).contains($0)
        })
    }
    
    func replacingCharacters(_ characters:CharacterSet, with newChar:Character) -> Self {
        String(self.compactMap( {
            CharacterSet(charactersIn: "\($0.1)").isSubset(of: characters)
             ? newChar : $0.1
        }))
    }
    
    func replacingCharacters(in string:String, with newChar:Character) -> Self {
        String(self.compactMap( {
            CharacterSet(charactersIn: "\($0)").isSubset(of: CharacterSet(charactersIn:string))
             ? newChar : $0
        }))
    }
}

用法:

print("hello \n my name\t is Joe".removingCharacters(.whitespacesAndNewlines))
print("hello \n my name\t is Joe".removingCharacters(in: " \t\n"))

print("ban annan anann ana".replacingCharacters(.whitespacesAndNewlines, with: "_"))
print("ban-annan anann ana".replacingCharacters(in: " -", with: "_"))

显然,对于单个字符,. replacingoccurrences (of: " ", with: "+")更好。

我没有做过性能比较

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

风格做在Ramis的扩展。如果有人愿意,我会很感兴趣的。

参见替换表情符号:https://stackoverflow.com/a/63416058/5946596