ios Swift startsWith 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32664543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:43:02  来源:igfitidea点击:

Swift startsWith method?

iosswift

提问by Arthur Garza

Is there such thing as a startsWith() method or something similar in Swift?

Swift 中是否有 startsWith() 方法或类似方法?

I'm basically trying to check if a certain string starts with another string. I also want it to be case insensitive.

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

As you might be able to tell, I'm just trying to do a simple search feature but I seem to be failing miserably at this.

正如您可能会说的那样,我只是想做一个简单的搜索功能,但我似乎在这方面失败了。

This is what I'd like:

这就是我想要的:

typing in "sa" should give me results for "San Antonio", "Santa Fe", etc. typing in "SA" or "Sa" or even "sA" should also return "San Antonio" or "Santa Fe".

输入“sa”应该会给我“San Antonio”、“Santa Fe”等的结果。输入“SA”或“Sa”甚至“sA”也应该返回“San Antonio”或“Santa Fe”。

I was using

我正在使用

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

prior to iOS9 and it was working just fine. After upgrading to iOS9, however, it stopped working and now searches are case sensitive.

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

回答by jobima

use hasPrefixinstead of startsWith.

使用hasPrefix代替startsWith.

Example:

例子:

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

回答by Oliver Atkinson

here is a Swift extension implementation of startsWith:

这是startsWith的Swift扩展实现:

extension String {

  func startsWith(string: String) -> Bool {

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

    return range.startIndex == startIndex
  }

}

Example usage:

用法示例:

var str = "Hello, playground"

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

回答by C?ur

To answer specifically case insensitiveprefix matching:

要特别回答不区分大小写的前缀匹配:

in pure Swift (recommended most of the time)

在纯 Swift 中(大部分时间推荐)

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

or:

或者:

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

note: for an empty prefix ""both implementations will return true

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

using Foundation range(of:options:)

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

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

note: for an empty prefix ""it will return false

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

and being ugly with a regex (I've seen it...)

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

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
    }
}

note: for an empty prefix ""it will return false

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

回答by Bueno

In swift 4 func starts<PossiblePrefix>(with possiblePrefix: PossiblePrefix) -> Bool where PossiblePrefix : Sequence, String.Element == PossiblePrefix.Elementwill be introduced.

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

Example Use:

使用示例:

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

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

回答by Gary Makin

Edit: updated for Swift 3.

编辑:为 Swift 3 更新。

The Swift String class does have the case-sensitive method hasPrefix(), but if you want a case-insensitive search you can use the NSString method range(of:options:).

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

Note: By default, the NSString methods are notavailable, but if you import Foundationthey are.

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

So:

所以:

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

The options can be given as either .caseInsensitiveor [.caseInsensitive]. You would use the second if you wanted to use additional options, such as:

选项可以作为.caseInsensitive或给出[.caseInsensitive]。如果您想使用其他选项,则可以使用第二个,例如:

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

This approach also has the advantage of being able to use other options with the search, such as .diacriticInsensitivesearches. The same result cannot be achieved simply by using . lowercased()on the strings.

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

回答by user2990759

Swift 3 version:

斯威夫特 3 版本:

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

回答by CaOs433

In Swift 4 with extensions

在带有扩展的 Swift 4 中

My extension-example contains 3 functions: check do a String startwith a subString, do a String endto a subString and do a String containsa subString.

我的扩展示例包含 3 个函数:检查以子字符串开头的字符串,以子字符串结尾的字符串和包含子字符串的字符串。

Set the isCaseSensitive-parameter to false, if you want to ignore is the characters "A" or "a", otherwise set it to true.

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

See the comments in the code for more information of how it works.

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

Code:

代码:

    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
            }
        }
    }

Examples how to use:

用法示例:

For checking do the String start with "TEST":

为了检查字符串是否以“TEST”开头:

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

For checking do the String start with "test":

为了检查字符串是否以“test”开头:

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

For checking do the String end with "G123":

检查以“G123”结尾的字符串:

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

For checking do the String end with "g123":

检查以“g123”结尾的字符串:

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

For checking do the String contains "RING12":

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

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

For checking do the String contains "ring12":

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

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