Swift startsWith方法?

时间:2015-09-19 05:18:26

标签: ios swift

在Swift中是否存在startsWith()方法或类似内容?

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

正如您可能会说的那样,我只是想尝试一个简单的搜索功能,但我似乎对此失败了。

这就是我想要的:

输入" sa"应该给我圣安东尼奥","圣达菲"等的结果。 输入" SA"或" Sa"甚至" sA"也应该回归圣安东尼奥"或者" Santa Fe"。

我正在使用

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 ");
    }

7 个答案:

答案 0 :(得分:325)

使用 hasPrefix 代替 startsWith

示例:

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

答案 1 :(得分:12)

这是startsWith的Swift扩展实现:

<Window.Resources>
    <Style TargetType="ToggleButton">
        <Setter Property="BorderThickness" Value="1" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ToggleButton">
                    <Border Name="border" Background="Transparent" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="Black">
                        <ContentPresenter/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsChecked" Value="True">
                <Setter Property="BorderThickness" Value="10" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>
<Grid>
    <ToggleButton>Hello World</ToggleButton>
</Grid>

使用示例:

extension String {

  func startsWith(string: String) -> Bool {

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

    return range.startIndex == startIndex
  }

}

答案 2 :(得分:7)

回答具体案例不敏感前缀匹配:

纯粹的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

答案 3 :(得分:6)

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

使用示例:

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

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

答案 4 :(得分:5)

编辑:为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])

答案 5 :(得分:1)

Swift 3版本:

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

答案 6 :(得分:1)

在带有扩展功能的Swift 4中

我的扩展示例包含3个功能:检查是否对子字符串进行字符串开始,对子字符串进行字符串结束和对字符串进行包含< / strong>一个子字符串。

如果要忽略的是字符“ 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