有什么办法可以替换Swift String上的字符吗?


474

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

示例:“这是我的字符串”

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

我该如何实现?


Answers:


912

此答案已针对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所指出的那样,optionsand range参数是可选的,因此,如果您不想指定字符串比较选项或范围以在其中进行替换,则只需执行以下操作。

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

或者,如果数据采用特定格式,例如您要替换的分隔字符,则可以使用components()将字符串拆分为and数组,然后可以使用join()函数将其与指定的分隔符放回原处。

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

或者,如果您正在寻找一种不使用NSString API的更快速的解决方案,则可以使用它。

let aString = "Some search text"

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

9
选项范围参数是可选的
cprcrack

1
stringByReplacingOccurrencesOfString的绝佳swift2替换
rjb101

我不知道我做错了什么,但是第二个Swift 2.0解决方案给我留下了可选字符串。原始字符串看起来像这样:"x86_64"新映射看起来就像"Optional([\"x\", \"8\", \"6\", \"_\", \"6\", \"4\"])"
John Shelley 2015年

7
对于任何stringByReplacingOccurrencesOfString在Swift 2中使用存在问题的人,您都需要import Foundation能够使用该方法。
Liron Yahdav 2015年

1
哇,stringByReplacingOccurrencesOfString,多么直观!我期待像makeNewStringByReplacingOccurrencesOfFirstArgumentByValueInSecondArgument之类的东西
Novellizator

64

您可以使用此:

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

2
我不会将函数命名为“ replace”,因为这表明它会使变量发生变化。使用与Apple相同的语法。称它为“ replaceing(_:withString :)”使它更加清晰。将来的变异“替换”功能在命名上也会发生冲突。
桑卡斯

57

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

这是这个问题的答案。
Bijender Singh Shekhawat

19

您是否测试过:

var test = "This is my string"

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

13

斯威夫特4:

let abc = "Hello world"

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

print(result :\(result))

输出:

result : Hello_world

9

我正在使用此扩展名:

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

8

与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?

7

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

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

4

基于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命名约定尝试提供合适的函数名称。


这是我的首选解决方案,因为它使您可以一次替换多个字符。
焚化炉

4

发生在我身上的事情较少,我只想在其中更改(单词或字符) 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

好的解决方案!谢谢
Dasoga

swift竭尽全力为几乎所有内容使用不同的术语。几乎所有其他语言replace
javadba


1

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

1

迅速扩展:

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以进行多个替换。


1

这是Swift 3的示例:

var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
   stringToReplace?.replaceSubrange(range, with: "your")
} 

1

在Swift 4.2中这很容易。只是replacingOccurrences(of: " ", with: "_")用于替换

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

1

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"

1
这是一个很棒的小窍门。谢谢狮子座!
彼得·苏瓦拉

0

如果您不想使用Objective-C NSString方法,则可以使用splitjoin

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"


0

我已经实现了这个非常简单的功能:

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

所以你可以这样写:

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

0

您可以测试一下:

让newString = test.stringByReplacingOccurrencesOfString(“”,withString:“ +”,选项:无,范围:无)


-1

这是上就地发生替换方法的扩展,该方法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"

如果目标文本中包含了所包含的文本,我已经更新了代码以防止无限循环。
斯特凡COPIN
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.