-1

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,

Fausto Checa
  • 163
  • 13
  • Wouldn't "Colon between each two digits" be "34:56:7"? what have you tried already? – Scriptable Oct 08 '18 at 08:30
  • 5
    `let result = String(number).map({String($0)}).joined(separator: ":")`? – Larme Oct 08 '18 at 08:31
  • it is between two consecutive digits, I have just corrected it. – Fausto Checa Oct 08 '18 at 08:35
  • Possible duplicate of [How add separator to string at every N characters in swift?](https://stackoverflow.com/questions/34454532/how-add-separator-to-string-at-every-n-characters-in-swift) – Cristik Oct 08 '18 at 11:08

2 Answers2

6

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.

Larme
  • 24,190
  • 6
  • 51
  • 81
1

You need to join it by :

use this

let result = String(number).map({String($0)}).joined(separator: ":")
Denis
  • 492
  • 2
  • 15