Swift startsWith方法?


151

在Swift中是否有诸如startsWith()方法之类的东西?

我基本上是在尝试检查某个字符串是否以另一个字符串开头。我也希望它不区分大小写。

如您所知,我只是在尝试做一个简单的搜索功能,但我似乎为此失败了。

这就是我想要的:

输入“ sa”应该给我“圣安东尼奥”,“圣达菲”等的结果。输入“ SA”或“ Sa”甚至是“ sA”也应该返回“圣安东尼奥”或“圣达菲”。

我在用

self.rangeOfString(find, options: NSStringCompareOptions.CaseInsensitiveSearch) != nil 

在iOS9之前的版本中,它运行良好。但是,升级到iOS9后,它停止工作,现在搜索区分大小写。

    var city = "San Antonio"
    var searchString = "san "
    if(city.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch) != nil){
        print("San Antonio starts with san ");
    }

    var myString = "Just a string with san within it"

    if(myString.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch) != nil){
        print("I don't want this string to print bc myString does not start with san ");
    }

您能否举一个具体的示例,其中带有CaseInsensitiveSearch的rangeOfString无法按预期工作?我已经在iOS 9模拟器中对其进行了测试,并且对我有用。
Martin R

Answers:


362

使用hasPrefix代替startsWith

例:

"hello dolly".hasPrefix("hello")  // This will return true
"hello dolly".hasPrefix("abc")    // This will return false

2
OP请求不区分大小写,你的答案是大小写敏感的
心教堂

13
使用"string".lowercased()
TotoroTotoro

12

这是startsWith的Swift扩展实现:

extension String {

  func startsWith(string: String) -> Bool {

    guard let range = rangeOfString(string, options:[.AnchoredSearch, .CaseInsensitiveSearch]) else {
      return false
    }

    return range.startIndex == startIndex
  }

}

用法示例:

var str = "Hello, playground"

let matches    = str.startsWith("hello") //true
let no_matches = str.startsWith("playground") //false

10

要专门回答不区分大小写的前缀匹配:

在纯Swift中(大多数时候推荐)

extension String {
    func caseInsensitiveHasPrefix(_ prefix: String) -> Bool {
        return lowercased().hasPrefix(prefix.lowercased())
    }
}

要么:

extension String {
    func caseInsensitiveHasPrefix(_ prefix: String) -> Bool {
        return lowercased().starts(with: prefix.lowercased())
    }
}

注意:对于空前缀,""两个实现都将返回true

使用基金会 range(of:options:)

extension String {
    func caseInsensitiveHasPrefix(_ prefix: String) -> Bool {
        return range(of: prefix, options: [.anchored, .caseInsensitive]) != nil
    }
}

注意:对于空前缀"",它将返回false

和正则表达式很丑陋(我见过...)

extension String {
    func caseInsensitiveHasPrefix(_ prefix: String) -> Bool {
        guard let expression = try? NSRegularExpression(pattern: "\(prefix)", options: [.caseInsensitive, .ignoreMetacharacters]) else {
            return false
        }
        return expression.firstMatch(in: self, options: .anchored, range: NSRange(location: 0, length: characters.count)) != nil
    }
}

注意:对于空前缀"",它将返回false


6

很快func starts<PossiblePrefix>(with possiblePrefix: PossiblePrefix) -> Bool where PossiblePrefix : Sequence, String.Element == PossiblePrefix.Element将介绍4 。

使用示例:

let a = 1...3
let b = 1...10

print(b.starts(with: a))
// Prints "true"

6

编辑:更新为Swift 3。

Swift String类确实具有区分大小写的方法hasPrefix(),但是如果您要进行不区分大小写的搜索,则可以使用NSString方法range(of:options:)

注意:默认情况下,NSString方法不可用,但如果可用,则不可用import Foundation

所以:

import Foundation
var city = "San Antonio"
var searchString = "san "
let range = city.range(of: searchString, options:.caseInsensitive)
if let range = range {
    print("San Antonio starts with san at \(range.startIndex)");
}

选项可以指定为.caseInsensitive[.caseInsensitive]。如果要使用其他选项,请使用第二个,例如:

let range = city.range(of: searchString, options:[.caseInsensitive, .backwards])

该方法还具有能够在搜索中使用其他选项(例如.diacriticInsensitive搜索)的优势。仅仅通过. lowercased()在字符串上使用无法获得相同的结果。


1

Swift 3版本:

func startsWith(string: String) -> Bool {
    guard let range = range(of: string, options:[.caseInsensitive]) else {
        return false
    }
    return range.lowerBound == startIndex
}

可以更快.anchored。请参阅我的答案或Oliver Atkinson的答案。
心教堂

1

在带有扩展功能的Swift 4中

我的扩展示例包含3个功能:检查以String 开头的subString为字符串,以String 结尾的subString以及包含 String的子字符串。

如果要忽略的是字符“ A”或“ a”,则将isCaseSensitive-parameter设置为false,否则将其设置为true。

有关其工作原理的更多信息,请参见代码中的注释。

码:

    import Foundation

    extension String {
        // Returns true if the String starts with a substring matching to the prefix-parameter.
        // If isCaseSensitive-parameter is true, the function returns false,
        // if you search "sA" from "San Antonio", but if the isCaseSensitive-parameter is false,
        // the function returns true, if you search "sA" from "San Antonio"

        func hasPrefixCheck(prefix: String, isCaseSensitive: Bool) -> Bool {

            if isCaseSensitive == true {
                return self.hasPrefix(prefix)
            } else {
                var thePrefix: String = prefix, theString: String = self

                while thePrefix.count != 0 {
                    if theString.count == 0 { return false }
                    if theString.lowercased().first != thePrefix.lowercased().first { return false }
                    theString = String(theString.dropFirst())
                    thePrefix = String(thePrefix.dropFirst())
                }; return true
            }
        }
        // Returns true if the String ends with a substring matching to the prefix-parameter.
        // If isCaseSensitive-parameter is true, the function returns false,
        // if you search "Nio" from "San Antonio", but if the isCaseSensitive-parameter is false,
        // the function returns true, if you search "Nio" from "San Antonio"
        func hasSuffixCheck(suffix: String, isCaseSensitive: Bool) -> Bool {

            if isCaseSensitive == true {
                return self.hasSuffix(suffix)
            } else {
                var theSuffix: String = suffix, theString: String = self

                while theSuffix.count != 0 {
                    if theString.count == 0 { return false }
                    if theString.lowercased().last != theSuffix.lowercased().last { return false }
                    theString = String(theString.dropLast())
                    theSuffix = String(theSuffix.dropLast())
                }; return true
            }
        }
        // Returns true if the String contains a substring matching to the prefix-parameter.
        // If isCaseSensitive-parameter is true, the function returns false,
        // if you search "aN" from "San Antonio", but if the isCaseSensitive-parameter is false,
        // the function returns true, if you search "aN" from "San Antonio"
        func containsSubString(theSubString: String, isCaseSensitive: Bool) -> Bool {

            if isCaseSensitive == true {
                return self.range(of: theSubString) != nil
            } else {
                return self.range(of: theSubString, options: .caseInsensitive) != nil
            }
        }
    }

示例如何使用:

为了进行检查,字符串以“ TEST”开头:

    "testString123".hasPrefixCheck(prefix: "TEST", isCaseSensitive: true) // Returns false
    "testString123".hasPrefixCheck(prefix: "TEST", isCaseSensitive: false) // Returns true

为了进行检查,字符串以“ test”开头:

    "testString123".hasPrefixCheck(prefix: "test", isCaseSensitive: true) // Returns true
    "testString123".hasPrefixCheck(prefix: "test", isCaseSensitive: false) // Returns true

为了进行检查,字符串以“ G123”结尾:

    "testString123".hasSuffixCheck(suffix: "G123", isCaseSensitive: true) // Returns false
    "testString123".hasSuffixCheck(suffix: "G123", isCaseSensitive: false) // Returns true

为了进行检查,字符串以“ g123”结尾:

    "testString123".hasSuffixCheck(suffix: "g123", isCaseSensitive: true) // Returns true
    "testString123".hasSuffixCheck(suffix: "g123", isCaseSensitive: false) // Returns true

为了进行检查,字符串是否包含“ RING12”:

    "testString123".containsSubString(theSubString: "RING12", isCaseSensitive: true) // Returns false
    "testString123".containsSubString(theSubString: "RING12", isCaseSensitive: false) // Returns true

为了进行检查,字符串是否包含“ ring12”:

    "testString123".containsSubString(theSubString: "ring12", isCaseSensitive: true) // Returns true
    "testString123".containsSubString(theSubString: "ring12", isCaseSensitive: false) // Returns true
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.