Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace characters in swift 3 string

Tags:

string

swift3

I need a function to replace numbers 0..9 with characters A..J consecutively. How can I write it in Swift 3? Swift 3 string manipulation is so weird :| I tried accessing characters and then adding and offset (shifting) characters, but have no success.

like image 936
AVEbrahimi Avatar asked May 15 '26 01:05

AVEbrahimi


1 Answers

Here is a possible solution to your problem which is also Unicode safe:

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

Explanation

Idea/Problem

Map each character of the string to another (or same) character: 0...9 -> A...J, everything else stays

Implementation

Use a lazy character collection for performance reasons for large strings. A non lazy one would create an intermediate Array.

The mapping from one to another character goes through the following process:

  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 { ... }
    
like image 121
Qbyte Avatar answered May 18 '26 08:05

Qbyte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!