Swift inizia con il metodo?


151

Esiste un metodo startWith () o qualcosa di simile in Swift?

Sto sostanzialmente cercando di verificare se una determinata stringa inizia con un'altra stringa. Voglio anche che non faccia distinzione tra maiuscole e minuscole.

Come potresti essere in grado di dire, sto solo cercando di fare una semplice funzione di ricerca, ma mi sembra che fallisca miseramente.

Questo è quello che mi piacerebbe:

digitando "sa" dovresti ottenere risultati per "San Antonio", "Santa Fe", ecc. digitando "SA" o "Sa" o anche "sA" dovrebbe anche restituire "San Antonio" o "Santa Fe".

Stavo usando

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

prima di iOS9 e funzionava bene. Dopo l'aggiornamento a iOS9, tuttavia, ha smesso di funzionare e ora le ricerche fanno distinzione tra maiuscole e minuscole.

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

Puoi fare un esempio concreto in cui rangeOfString con CaseInsensitiveSearch non funziona come previsto? L'ho testato nel simulatore iOS 9 e ha funzionato per me.
Martin R

Risposte:


362

utilizzare hasPrefixinvece di startsWith.

Esempio:

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

2
Il PO chiede la distinzione tra maiuscole e minuscole e la tua risposta fa distinzione tra maiuscole
Cœur

13
È molto semplice rendere minuscole le stringhe prima del confronto utilizzando"string".lowercased()
TotoroTotoro,

12

ecco un'implementazione dell'estensione Swift di startWith:

extension String {

  func startsWith(string: String) -> Bool {

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

    return range.startIndex == startIndex
  }

}

Esempio di utilizzo:

var str = "Hello, playground"

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

10

Per rispondere in modo specifico alla corrispondenza dei prefissi senza distinzione tra maiuscole e minuscole :

in puro Swift (consigliato la maggior parte delle volte)

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

o:

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

nota: per un prefisso vuoto ""verranno restituite entrambe le implementazionitrue

utilizzando Foundation range(of:options:)

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

nota: per un prefisso vuoto ""torneràfalse

ed essere brutto con una regex (l'ho visto ...)

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

nota: per un prefisso vuoto ""torneràfalse


6

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

Esempio di utilizzo:

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

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

6

Modifica: aggiornato per Swift 3.

La classe Swift String ha il metodo con distinzione tra maiuscole e minuscole hasPrefix(), ma se si desidera una ricerca senza distinzione tra maiuscole e minuscole è possibile utilizzare il metodo NSString range(of:options:).

Nota: per impostazione predefinita, i metodi NSString non sono disponibili, ma se import Foundationlo sono.

Così:

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

Le opzioni possono essere fornite come .caseInsensitiveo [.caseInsensitive]. Utilizzeresti il ​​secondo se desideri utilizzare opzioni aggiuntive, come:

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

Questo approccio ha anche il vantaggio di poter utilizzare altre opzioni con la ricerca, come le .diacriticInsensitivericerche. Lo stesso risultato non può essere raggiunto semplicemente usando . lowercased()le stringhe.


1

Versione Swift 3:

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

può essere più veloce con .anchored. Vedi la mia risposta o la risposta di Oliver Atkinson.
Cœur il

1

In Swift 4 con estensioni

Il mio esempio di estensione contiene 3 funzioni: spuntare fare un inizio stringa con una sottostringa, fare una fine stringa a una sottostringa e fare una stringa contiene una sottostringa.

Impostare il parametro isCaseSensitive su false, se si desidera ignorare i caratteri "A" o "a", altrimenti impostarlo su true.

Vedi i commenti nel codice per maggiori informazioni su come funziona.

Codice:

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

Esempi su come usare:

Per il controllo, iniziare la stringa con "TEST":

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

Per il controllo, iniziare la stringa con "test":

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

Per il controllo, la stringa termina con "G123":

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

Per il controllo, la stringa termina con "g123":

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

Per il controllo, la stringa contiene "RING12":

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

Per il controllo, la stringa contiene "ring12":

    "testString123".containsSubString(theSubString: "ring12", isCaseSensitive: true) // Returns true
    "testString123".containsSubString(theSubString: "ring12", isCaseSensitive: false) // Returns true
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.