简体   繁体   中英

insert a character inside an Int Swift

I have a number, I want to insert a column ":" between each two consecutive digits inside that number, and get a String as a result

For example:

let number: Int = 34567  
let result: String = "3:4:5:6:7"

Thanks for any help,

Possible solution:

let result = String(number).map({ String($0) }).joined(separator: ":")

With explanation of intermediary results to help understand what's going on on theses 3 chained methods:

let interemdiary1 = String(number)
print("interemdiary1: \(interemdiary1)")
let interemdiary2 = interemdiary1.map({ String($0 )})
print("interemdiary2: \(interemdiary2)")
let interemdiary3 = interemdiary2.joined(separator: ":")
print("interemdiary3: \(interemdiary3)")

Output:

$>interemdiary1: 34567
$>interemdiary2: ["3", "4", "5", "6", "7"]
$>interemdiary3: 3:4:5:6:7

First, let's transform your number into a String.
Then, let's create an array of it where each character (as a String ) of the previous result is an element of it. I used a map() of it.
Finally, we use joined(separator:) to assemble them.

Another kind of solution can be found there: How add separator to string at every N characters in swift? It's just that you do it each 1 characters.

You need to join it by :

use this

let result = String(number).map({String($0)}).joined(separator: ":")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM