Reputation: 13
How to get the last 8 characters in array of string on swift2?
Hello I am working on a project which matching each users' contacts. I am using swiftAddressBook to fetch the phone numbers in the users' address book.
However, since some users typed their friends' phone numbers with area codes but some don't. Those with area codes could not match with those without area codes. (e.g. 88612345678 and 12345678). How should I tackle this issue?
I have some rough ideas but not sure how it works. Since I don't need exact matching all the numbers, I can tolerate some miss match. To give the life easier, it could be only matching the last 8 characters of the phone arrays. e.g. ["88612345678", "98765432", "55587654321"] to be ["12345678", "98765432", "87654321"]
I tried I can use
string.characters.suffix(8)
it is only for a string. Should I use for-loop to get all values of a array and then suffix the last 8 characters append it back to an array? I apology for my insufficient skills on array and string...Thank you for your help in advance.
Upvotes: 1
Views: 131
Reputation: 236418
let stringArray = ["88612345678", "98765432", "55587654321"]
let result = stringArray.map{String($0.characters.suffix(8))}
print(result) // "["12345678", "98765432", "87654321"]\n"
Upvotes: 1
Reputation: 285150
Alternatively
let array = ["88612345678", "98765432", "55587654321"]
let trimmedArray = array.map { $0.substringFromIndex($0.endIndex.advancedBy(-8)) }
Upvotes: 0
Reputation: 38162
Try this out:
let myArray : Array<String> = ["88612345678", "98765432", "55587654321"]
var newArray = [String]()
for myString in myArray {
if (count(myString) > 8) {
var index = advance(myString.endIndex, -8) // For swift 2 use var index = myString.endIndex.advanceBy(-8)
let newString = myString.substringFromIndex(index)
newArray.append(newString)
} else {
newArray.append(myString)
}
}
print(newArray) // prints ["12345678", "98765432", "87654321"]
Upvotes: 0
Reputation: 18181
An elegant solution:
var x = ["88612345678", "98765432", "55587654321"]
x.map({ $0.suffix(8) }).map(String.init) // there you go!
Upvotes: 1