在Swift 3中替换字符串中的字符

3

我需要一个函数来将数字0到9连续替换为字母A到J。请问在Swift 3中如何编写这个函数? Swift 3字符串操作非常奇怪:| 我尝试访问字符并添加偏移量(移位)字符,但没有成功。


看到你尝试过什么会很有帮助。 - Qbyte
1个回答

4

这里提供了一个可能解决您问题的方案,同时保证Unicode安全:

let string = "0123456789 abc xyz 9876543210"
// upper case A...J use 65; lower case a...j use 97
let shift = 65
let convertedString = String(string.characters.lazy.map{ char in
    Int(String(char)).map{ Character(UnicodeScalar($0 + shift)!) } ?? char
})

解释

思路/问题

将字符串中的每个字符映射到另一个(或同一)字符:0...9 -> A...J,其他字符保持不变。

实现

为了处理大型字符串,使用懒字符集提高性能。非懒惰的字符集会创建一个中间数组。

从一个字符映射到另一个字符的过程如下:

  1. Try to convert the character to an Int (Here Int?)

    1.1 If it fails (is nil) the nil coalescing operator (??) comes in to play and the input character is returned

  2. The Int value ($0) now gets converted back to a Character through its (shifted) ASCII representation ASCII Table

  3. Convert the lazily mapped collection to a String. Swifts declaration of the initialiser:

    public init<S : Sequence>(_ characters: S)
        where S.Iterator.Element == Character { ... }
    

你为什么使用lazy进行映射?这样做有什么优势? - Noah Wilder
简而言之:如果我们不使用lazy,则会创建一个字符的中间数组,如果字符串本身很长,则需要大量的内存。请参见上面的实现部分以获取完整的解释。 - Qbyte

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