Reputation: 2024
How to replace number string with its corresponding Alphabet Characters in Array.
Example:
["1","2","3","3","2","3"]
Replace: 1 -> A, 2-> B, 3-> C
Result should be
["A","B","C","C","B","C"]
Upvotes: 0
Views: 123
Reputation: 6114
You may use Dictionary
for replacement rules:
let array = ["1", "2", "3", "3", "2", "3"]
let replacementRules = ["1": "A", "2": "B", "3": "C"]
let result = array.map{replacementRules[$0] ?? $0}
print(result)
//["A", "B", "C", "C", "B", "C"]
Upvotes: 3
Reputation: 1472
var arr = ["1","2","3","3","2","3"]
for i in 0..<arr.count {
switch(arr[i]) {
case "1":
arr[i] = "A"
break
case "2":
arr[i] = "B"
break
case "3":
arr[i] = "C"
break
default: break
}
}
Upvotes: 1
Reputation: 72420
If your array contain string value till 1-26, you can try like this
let alphabetArray = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
let arr = ["1","2","3","3","2","3"]
var newArr = [String]()
newArr = arr.map { (item) in
alphabetArray[Int(item)! - 1]
}
print(newArr)
Upvotes: 1