有没有一种方法可以在Swift字符串中替换字符?

587
我正在寻找一种方法来替换Swift中的字符String
例如:"This is my string"
我想将" "替换为"+",以便得到"This+is+my+string"。
我该如何实现?

Swift Extension - Juan Boero
24个回答

6

我的情况比较简单,我只想在字符串中更改一个词或者字符。

所以我使用了字典(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 即可。 - WestCoastProjects

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

为什么我在 String 中找不到 replacingOccurrences 方法? - WestCoastProjects
请确保您的变量类型为String。 - Yash Gotecha

4

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
这是一个很棒的小贴士。谢谢Leo! - Peter Suwara

3
自从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了,您会感到一帆风顺。

试试它,看看它是否有帮助!


3
在Swift 4.2中,这很容易。只需使用replacingOccurrences(of: " ", with: "_")进行替换即可。
var myStr = "This is my string"
let replaced = myStr.replacingOccurrences(of: " ", with: "_")
print(replaced)

2
这是Swift 3的示例:
var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
   stringToReplace?.replaceSubrange(range, with: "your")
} 

2
从开始,我们可以在RangeReplaceableCollection上使用新方法{{link1:replace(_:with:maxReplacements:)}},该方法将Regex作为参数,我们可以自定义请求。
var myString = "This is my string"
myString.replace(" ", with: "+")

但不要忘记 import RegexBuilder 以启用此功能


2
我实现了这个非常简单的函数:

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

所以,您可以编写:
let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')

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"

我已经更新了代码,以防止如果包含的文本在目标文本中出现时出现无限循环。 - Stéphane Copin

1

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数组来进行多个替换。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接