简体   繁体   English

如何快速获取字符串数组中的最后8个字符?

[英]How to get the last 8 characters in array of string on swift?

How to get the last 8 characters in array of string on swift2? 如何在swift2上获取字符串数组的最后8个字符?

eg ["88612345678", "98765432", "55587654321"] to be ["12345678", "98765432", "87654321"] 例如[[88612345678“,” 98765432“,” 55587654321“]为[” 12345678“,” 98765432“,” 87654321“]

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. 我正在使用swiftAddressBook来获取用户通讯簿中的电话号码。

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. 具有区号的用户不能与没有区号的用户匹配。 (eg 88612345678 and 12345678). (例如88612345678和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. 为了使生活更轻松,可能只匹配电话阵列的最后8个字符。 eg ["88612345678", "98765432", "55587654321"] to be ["12345678", "98765432", "87654321"] 例如[[88612345678“,” 98765432“,” 55587654321“]为[” 12345678“,” 98765432“,” 87654321“]

I tried I can use 我试过可以用

string.characters.suffix(8) 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? 我应该使用for-loop来获取数组的所有值,然后在后缀8个字符后将其附加回数组吗? I apology for my insufficient skills on array and string...Thank you for your help in advance. 对于数组和字符串方面的技能不足,我深表歉意。谢谢您的帮助。

An elegant solution: 优雅的解决方案:

var x = ["88612345678", "98765432", "55587654321"]

x.map({ $0.suffix(8) }).map(String.init) // there you go!
let stringArray = ["88612345678", "98765432", "55587654321"]
let result = stringArray.map{String($0.characters.suffix(8))}

print(result)  // "["12345678", "98765432", "87654321"]\n"

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"]

Alternatively 另外

let array = ["88612345678", "98765432", "55587654321"]
let trimmedArray = array.map { $0.substringFromIndex($0.endIndex.advancedBy(-8)) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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