Swift rangeOfString索引0或1

时间:2016-11-05 22:52:24

标签: swift string

我有一个名字数组,想要从第一个或第二个字母过滤出那些" E",来自以下数组

var userNames = ["John","Tom","Ed","Ben","Albert"]

输出应该是[" Ed"," Ben"]。阿尔伯特不应该被包括在内,因为这个职位不是第一名或第二名

let filteredNames = userName.filter { (inputStr) -> Bool in

     if let inputRang =  inputStr.range(of: "e", options: .caseInsensitive, range: nil, locale: nil)
     {
        //How do I check the position 0 or 1 here

        return true
    }
    return false
}

2 个答案:

答案 0 :(得分:2)

@Eendje发布了一个有效的解决方案来实现您的目标,但要回答您的问题 直接问题:您必须计算距离 从字符串初始索引(inputStr.startIndex)到位置 找到子字符串的位置(inputRange.lowerBound):

let filteredNames = userNames.filter { (inputStr) -> Bool in
    if let inputRange = inputStr.range(of: "e", options: .caseInsensitive) {
        if inputStr.distance(from: inputStr.startIndex, to: inputRange.lowerBound) <= 1 {
            return true
        }
    }
    return false
}

另一个选择是限制搜索范围:

let filteredNames = userNames.filter { (inputStr) -> Bool in
    let range = inputStr.startIndex ..< inputStr.index(inputStr.startIndex, offsetBy: 2)
    return inputStr.range(of: "e", options: .caseInsensitive, range: range) != nil
}

答案 1 :(得分:1)

let result = userNames.filter { $0.lowercased().characters.prefix(2).contains("e") }

print(result) // ["Ed", "Ben"]

这应该这样做。