arrays - 替换数组中的多次出现 - Swift 4.1

标签 arrays swift string replace swift-extensions

替换数组中的多次出现

swift 4.1,Xcode 9.3

我想做一个扩展,就像我为 ArrayString 做的扩展一样。


字符串扩展:

public extension String {
    
    ///
    /// Replaces multiple occurences of strings/characters/substrings with their associated values.
    /// ````
    /// var string = "Hello World"
    /// let newString = string.replacingMultipleOccurrences(using: (of: "l", with: "1"), (of: "o", with: "0"), (of: "d", with: "d!"))
    /// print(newString) //"He110 w0r1d!"
    /// ````
    /// 
    /// - Returns:
    /// String with specified parts replaced with their respective specified values.
    /// 
    /// - Parameters:
    ///     - array: Variadic values that specify what is being replaced with what value in the given string 
    ///
    public func replacingMultipleOccurrences<T: StringProtocol, U: StringProtocol>(using array: (of: T, with: U)...) -> String {
        var str = self
        for (a, b) in array {
            str = str.replacingOccurrences(of: a, with: b)
        }
        return str
    }

}

用法:

var string = "Hello World"
let newString = string.replacingMultipleOccurrences(using: (of: "l", with: "1"), (of: "o", with: "0"), (of: "d", with: "d!"))
print(newString) //"He110 w0r1d!"

到目前为止,我对数组的相同尝试

public extension Array {
    public func replacingMultipleOccurrences(using array: (of: Element, with: Element)...) -> Array {
        
        var newArr : Array<Element> = self
        var arr = array.filter { (arg) -> Bool in
            let (a, b) = arg
            return newArr.contains(a)
        }          
        for (i,e) in self.enumerated() {
            for (a,b) in arr {
                if e == a {
                    newArr[i] = b
                }
            }
        }
        return newArr
    }
}

注意: 目前,此扩展程序会产生大量错误。

理想用法:

let arr = [1,2,3,4,5,6,7,8,9]
let newArr = arr.replacingMultipleOccurrences(using: (of: 2, with: 20), (of: 3, with: 30), (of: 5, with: 50), (of: 8, with: 80), (of: 9, with: 90))
print(newArr) //[1,20,30,4,50,6,7,80,90]

我如何实现这个理想(最好以尽可能最有效的方式)?

最佳答案

extension Array where Element: Equatable {
func replacingMultipleOccurrences(using array: (of: Element, with: Element)...) -> Array {
    var newArr: Array<Element> = self

    for replacement in array {
        for (index, item) in self.enumerated() {
            if item == replacement.of {
                newArr[index] = replacement.with
            }
        }
    }

    return newArr
  }
}

关于arrays - 替换数组中的多次出现 - Swift 4.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50026187/

相关文章:

c - 将单个字符数组转换为一个多维数组

ios - Xcode Swift appleWatch 读取应用程序 UserDefaults?

python - 如何缩短这个替换密码?

java - 初学编程练习(Java): recursively counting instances of substring in string (. equals()?)

php - 如果数组与 mysql 中的数组匹配

c - 在循环中打印字符串数组

javascript - 一种在 JavaScript 数组中查找最接近值的算法

swift - 在 SPM(Swift 包管理器)中导入 .framework

ios - 当 View 出现在屏幕上时,如何让键盘将 View 向上推? Xcode swift

java - 在 Java 中使用递归的字符串排列