1

i was trying to add comma to the string after every third character.

my code looks like this

var str = "12345678912345"

for (index,item) in str.enumerated() {
    if index % 3 == 0 {
        str.insert(",", at: str.index(of: item)!)
    }
}
print(str)

i expect the output "123,456,789,123,45" but the actual output is ",123,,456,78912345".

i can't work with Int or Double and use NumberFormatter because input could be more than Int or Double max values.

  • Try this solution, Someone might be knowing a better way, but this will also work.. let str = "12345678912345" var newStr = "" for (index,item) in str.enumerated() { if index % 3 == 0 { if newStr == "" { newStr = item.description } else { newStr = newStr + "," + item.description } } else { newStr = newStr + item.description } } print(newStr) – manishsharma93 Jul 24 '19 at 13:06
  • This is a pretty naive solution, but you can easily modify your existing code like this ```var offsets = [Int]() var str = "12345678912345" for (index,item) in str.enumerated() { if (index + 1) % 3 == 0 { offsets.append(index + 1) } } var commasAdded = 0 for offset in offsets{ if offset + commasAdded < str.count{ str.insert(",", at: String.Index(encodedOffset: offset + commasAdded)) } commasAdded += 1 } print(str)``` sorry for formatting, but I can't submit as an answer because the question was closed – LulzCow Jul 24 '19 at 18:48

0 Answers0