2015-04-02 17 views
24

Come ottengo la stringa prima di un determinato carattere in rapido? Il codice sotto è come l'ho fatto nell'Objective C, ma non riesco a svolgere lo stesso compito in Swift. Qualche consiglio o suggerimento su come ottenere questo risultato? rangeOfString sembra non funzionare affatto in modo rapido (anche se Swift ha agito di nuovo per me).Swift: come ottenere la stringa prima di un determinato carattere?

NSRange range = [time rangeOfString:@" "]; 
NSString *startDate = 
[time substringToIndex:range.location]; 

Come si può vedere dal codice di cui sopra sono in grado di ottenere la stringa prima del carattere di spazio in Objective C.

Edit: Se provo qualcosa di simile

var string = "hello Swift" 
var range : NSRange = string.rangeOfString("Swift") 

I ottenere il seguente errore.

Impossibile convertire il tipo di espressione 'NSString' digitare '(String, opzioni: NSStringCompareOptions, gamma: Gamma ?, locale:? NSLocale)'

Non so cosa ho fatto di sbagliato esattamente o come risolverlo correttamente.

+0

In [questa risposta] (http: // StackOverflow.it/a/24161872/2240769) usano anche rangeOfString in Swift e sembra funzionare. –

+0

Ho modificato la mia domanda per spiegare meglio cosa sta succedendo quando provo ad applicare la soluzione. –

+0

Puoi usare 'Range' invece di' NSRange': 'lasciare range: Range? = string.rangeOfString ("Swift") '. Puoi anche lanciare 'String' su' NSString': 'var range: NSRange = (stringa come NSString) .rangeOfString (" Swift ")' – albertamg

risposta

56

Usa componentsSeparatedByString(), come illustrato di seguito:

var delimiter = " " 
var newstr = "token0 token1 token2 token3" 
var token = newstr.componentsSeparatedByString(delimiter) 
print (token[0]) 

O, per usare il tuo caso specifico:

var delimiter = " token1" 
var newstr = "token0 token1 token2 token3" 
var token = newstr.componentsSeparatedByString(delimiter) 
print (token[0]) 

Swift 3 EDIT:

Con Swift 3, il metodo di cui sopra non funziona più, utilizzare invece quanto segue:

var token = newstr.components(separatedBy: delimiter) 

Se questa modifica l'ha aiutata, si prega di aumentare di valore lo this answer.

+0

Risposta fantastica. Stavo cercando di capire come eseguire questo compito con rangeOfString, ma questo è MOLTO più efficiente. – Adrian

15

Si può fare lo stesso con rangeOfString() fornito da String classe

let string = "Hello Swift" 
if let range = string.rangeOfString("Swift") { 
    let firstPart = string[string.startIndex..<range.startIndex] 
    print(firstPart) // print Hello 
} 

È possibile anche realizzarlo con il vostro metodo di substringToIndex()

let string = "Hello Swift" 
if let range = string.rangeOfString("Swift") { 
    firstPart = string.substringToIndex(range.startIndex) 
    print(firstPart) // print Hello 
} 

Swift 3 UPDATE:

let string = "Hello Swift" 
if let range = string.range(of: "Swift") { 
    let firstPart = string[string.startIndex..<range.lowerBound] 
    print(firstPart) // print Hello 
} 
.210

Spero che questo può aiutare;)

3

Se si desidera una soluzione che non comporta tirando in fondazione, è possibile farlo con find e affettare:

let str = "Hello, I must be going." 

if let comma = find(str, ",") { 
    let substr = str[str.startIndex..<comma] 
    // substr will be "Hello" 
} 

Se si vuole esplicitamente un vuoto stringa nel caso in cui non viene trovato alcun tale carattere, è possibile utilizzare l'operatore nil-coalescenza:

let str = "no comma" 
let comma = find(str, ",") ?? str.startIndex 
let substr = str[str.startIndex..<comma] // substr will be "" 

nota, a differenza della tecnica componentsSeparatedByString, questo non richiede la creazione di un array, e onl y richiede la scansione fino alla prima occorrenza del personaggio piuttosto che spezzare l'intera stringa nell'array delimitato da caratteri.

+0

sì ... funziona ... ma cosa succede se voglio ottenere una stringa dopo un certo carattere? –

+0

@Bhavin 'find (str,", ") ?. successore()' –

+2

@all 'find' è ** non più ** supportato in Swift 2.0 – Honey

1

È possibile utilizzare rangeOfString, ma restituisce un tipo Range<String.Index>, non un NSRange:

let string = "hello Swift" 
if let range = string.rangeOfString("Swift") { 
    print(string.substringToIndex(range.startIndex)) 
} 
2

di mutare una stringa in parte fino a quando la prima apparizione di una stringa specificata si potrebbe estendere la stringa in questo modo:

extension String { 

    mutating func until(_ string: String) { 
     var components = self.components(separatedBy: string) 
     self = components[0] 
    } 

} 

questo può essere chiamato come questo allora:

var foo = "Hello Swift" 
foo.until(" Swift") // foo is now "Hello" 
0

I miei 2 centesimi :-) utilizzando Swift 3.0, simile a PHP strstr

extension String { 

    func strstr(needle: String, beforeNeedle: Bool = false) -> String? { 
     guard let range = self.range(of: needle) else { return nil } 

     if beforeNeedle { 
      return self.substring(to: range.lowerBound) 
     } 

     return self.substring(from: range.upperBound) 
    } 

} 

usage1

"Hello, World!".strstr(needle: ",", beforeNeedle: true) // returns Hello 

usage2

"Hello, World!".strstr(needle: " ") // returns World! 
3

Facendo seguito alla risposta di Syed Tariq: Se vuoi solo la stringa prima del delimitatore (altrimenti, y ou riceve una matrice [String]):

var token = newstr.components(separatedBy: delimiter).first 
+0

Questo ha funzionato per me. Grazie. – waseefakhtar

1
let string = "Hello-world" 
if let range = string.range(of: "-") { 
let firstPart = string[(string.startIndex)..<range.lowerBound] 
print(firstPart) 
} 

uscita è: Ciao

0

Qui di seguito è una specie di tutta una combo

let string = "This a string split using * and this is left." 
if let range = string.range(of: "*") { 
    let lastPartIncludingDelimiter = string.substring(from: range.lowerBound) 
    print(lastPartIncludingDelimiter) // print * and this is left. 

    let lastPartExcludingDelimiter = string.substring(from: range.upperBound) 
    print(lastPartExcludingDelimiter) // print and this is left. 

    let firstPartIncludingDelimiter = string.substring(to: range.upperBound) 
    print(firstPartIncludingDelimiter) // print This a string split using * 

    let firstPartExcludingDelimiter = string.substring(to: range.lowerBound) 
    print(firstPartExcludingDelimiter) // print This a string split using 
} 
Problemi correlati