Swift: podziel ciąg znaków na tablicę

Powiedzmy, że mam tu ciąg znaków:

var fullName: String = "First Last"

Chcę podzielić bazę łańcuchów na białe spacje i przypisać wartości do odpowiednich zmiennych

var fullNameArr = // something like: fullName.explode(" ") 

var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]

Ponadto, czasami użytkownicy mogą nie mieć nazwiska.

Author: Sruit A.Suk, 2014-09-05

30 answers

Sposobem Swift jest użycie globalnej funkcji split, w ten sposób:

var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil

Z Swift 2

W Swift 2 użycie split staje się nieco bardziej skomplikowane ze względu na wprowadzenie wewnętrznego typu CharacterView. Oznacza to, że String nie przyjmuje już protokołów SequenceType ani CollectionType i zamiast tego należy użyć właściwości .characters, aby uzyskać dostęp do reprezentacji typu CharacterView instancji łańcuchowej. (Uwaga: CharacterView przyjmuje Sekwencetype i Protokoły typu CollectionType).

let fullName = "First Last"
let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init)
// or simply:
// let fullNameArr = fullName.characters.split{" "}.map(String.init)

fullNameArr[0] // First
fullNameArr[1] // Last 
 706
Author: Ethan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-13 12:14:08

Po prostu wywołaj componentsSeparatedByString metodę na swoim fullName

import Foundation

var fullName: String = "First Last"
let fullNameArr = fullName.componentsSeparatedByString(" ")

var firstName: String = fullNameArr[0]
var lastName: String = fullNameArr[1]

Aktualizacja dla Swift 3+

import Foundation

let fullName    = "First Last"
let fullNameArr = fullName.components(separatedBy: " ")

let name    = fullNameArr[0]
let surname = fullNameArr[1]
 837
Author: Chen-Tsu Lin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-22 01:41:57

najprostszą metodą jest użycie komponentów rozdzielonych przez:

Dla Swift 2:

import Foundation
let fullName : String = "First Last";
let fullNameArr : [String] = fullName.componentsSeparatedByString(" ")

// And then to access the individual words:

var firstName : String = fullNameArr[0]
var lastName : String = fullNameArr[1]

Dla Swift 3:

import Foundation

let fullName : String = "First Last"
let fullNameArr : [String] = fullName.components(separatedBy: " ")

// And then to access the individual words:

var firstName : String = fullNameArr[0]
var lastName : String = fullNameArr[1]
 150
Author: WMios,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-16 15:30:52

Swift Dev. 4.0 (Maj 24, 2017)

Nowa funkcja split W Swift 4 (Beta ).

import Foundation
let sayHello = "Hello Swift 4 2017";
let result = sayHello.split(separator: " ")
print(result)

Wyjście:

["Hello", "Swift", "4", "2017"]

Dostęp do wartości:

print(result[0]) // Hello
print(result[1]) // Swift
print(result[2]) // 4
print(result[3]) // 2017

Xcode 8.1 / Swift 3.0.1

Oto sposób wielu ograniczników z tablicą.

import Foundation
let mathString: String = "12-37*2/5"
let numbers = mathString.components(separatedBy: ["-", "*", "/"])
print(numbers)

Wyjście:

["12", "37", "2", "5"]
 87
Author: LugiHaue,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-22 11:13:57

Jako alternatywę dla odpowiedzi WMios, możesz również użyć componentsSeparatedByCharactersInSet, co może być przydatne w przypadku, gdy masz więcej separatorów (spacja, przecinek, itp.).

Z twoim konkretnym wkładem:

let separators = NSCharacterSet(charactersInString: " ")
var fullName: String = "First Last";
var words = fullName.componentsSeparatedByCharactersInSet(separators)

// words contains ["First", "Last"]

Użycie wielu separatorów:

let separators = NSCharacterSet(charactersInString: " ,")
var fullName: String = "Last, First Middle";
var words = fullName.componentsSeparatedByCharactersInSet(separators)

// words contains ["Last", "First", "Middle"]
 46
Author: Antonio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-16 05:03:27

Swift 4

let words = "these words will be elements in an array".components(separatedBy: " ")
 41
Author: Bobby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-10 23:28:09

Xcode 9 Swift 4 lub Xcode 8.2.1 * Swift 3.0.2

Jeśli potrzebujesz tylko poprawnie sformatować nazwę osoby, możesz użyć PersonNameComponentsFormatter .

Klasa PersonNameComponentsFormatter zapewnia zlokalizowane reprezentacje składników nazwiska danej osoby, jak reprezentowane przez obiekt PersonNameComponents. Użyj tej klasy, aby utworzyć zlokalizowane nazwy podczas wyświetlania informacji o nazwie osoby do użytkownik.


// iOS (9.0 and later), macOS (10.11 and later), tvOS (9.0 and later), watchOS (2.0 and later)
let nameFormatter = PersonNameComponentsFormatter()

let name =  "Mr. Steven Paul Jobs Jr."
// personNameComponents requires iOS (10.0 and later)
if let nameComps  = nameFormatter.personNameComponents(from: name) {
    nameComps.namePrefix   // Mr.
    nameComps.givenName    // Steven
    nameComps.middleName   // Paul
    nameComps.familyName   // Jobs
    nameComps.nameSuffix   // Jr.

    // It can also be convufgured to format your names
    // Default (same as medium), short, long or abbreviated

    nameFormatter.style = .default
    nameFormatter.string(from: nameComps)   // "Steven Jobs"

    nameFormatter.style = .short
    nameFormatter.string(from: nameComps)   // "Steven"

    nameFormatter.style = .long
    nameFormatter.string(from: nameComps)   // "Mr. Steven Paul Jobs jr."

    nameFormatter.style = .abbreviated
    nameFormatter.string(from: nameComps)   // SJ

    // It can also be use to return an attributed string using annotatedString method
    nameFormatter.style = .long
    nameFormatter.annotatedString(from: nameComps)   // "Mr. Steven Paul Jobs jr."
}

Tutaj wpisz opis obrazka

 35
Author: Leo Dabus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-21 18:30:48

Problem z białymi spacjami

Ogólnie rzecz biorąc, ludzie wymyślają ten problem i złe rozwiązania w kółko. Czy to miejsce? ""a co z "\n", "\ t " lub jakimś białym znakiem unicode, którego nigdy nie widziałeś, w dużej mierze dlatego, że jest niewidoczny. While you can get away with

Słabe rozwiązanie

import Foundation
let pieces = "Mary had little lamb".componentsSeparatedByString(" ")

Jeśli kiedykolwiek będziesz potrzebował uścisnąć dłoń na rzeczywistości, obejrzyj wideo WWDC na strunach lub randkach. Krótko mówiąc, prawie zawsze lepiej jest pozwolić Apple rozwiązać ten rodzaj przyziemne zadanie.

Solidne Rozwiązanie: Użyj NSCharacterSet

Aby zrobić to poprawnie, IMHO, należy użyć NSCharacterSet, ponieważ jak wspomniano wcześniej, białe znaki mogą nie być tym, czego oczekujesz, a Apple dostarczyło zestaw znaków. Aby zapoznać się z różnymi dostarczonymi zestawami znaków, sprawdź dokumentację programisty Nscharacterset firmy Apple , a następnie rozszerz lub zbuduj nowy zestaw znaków, jeśli nie pasuje do Twoich potrzeb.

NSCharacterSet whitespaces

Zwraca zestaw znaków zawierający znaki w Unicode ogólne Kategoria Zs i tabulacja znaków (U + 0009).

let longerString: String = "This is a test of the character set splitting system"
let components = longerString.components(separatedBy: .whitespaces)
print(components)
 24
Author: Cameron Lowell Palmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-21 09:37:14

Swift 4 znacznie ułatwia dzielenie znaków, wystarczy użyć nowej funkcji split dla ciągów.

Przykład: let s = "hi, hello" let a = s.split(separator: ",") print(a)

Teraz masz tablicę z 'cześć' i 'cześć'.

 20
Author: Jeroen Zonneveld,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-10 18:03:44

Swift 3

let line = "AAA    BBB\t CCC"
let fields = line.components(separatedBy: .whitespaces).filter {!$0.isEmpty}
  • zwraca trzy ciągi AAA, BBB oraz CCC
  • filtruje puste pola
  • obsługuje wiele spacji i znaków tabulacji
  • Jeśli chcesz obsługiwać nowe linie, zamień .whitespaces na .whitespacesAndNewlines
 13
Author: tepl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-16 19:36:02

Xcode 8.0 / Swift 3

let fullName = "First Last"
var fullNameArr = fullName.components(separatedBy: " ")

var firstname = fullNameArr[0] // First
var lastname = fullNameArr[1] // Last

Długa Droga:

var fullName: String = "First Last"
fullName += " " // this will help to see the last word

var newElement = "" //Empty String
var fullNameArr = [String]() //Empty Array

for Character in fullName.characters {
    if Character == " " {
        fullNameArr.append(newElement)
        newElement = ""
    } else {
        newElement += "\(Character)"
    }
}


var firsName = fullNameArr[0] // First
var lastName = fullNameArr[1] // Last
 12
Author: NikaE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-04 20:14:21

Znalazłem ciekawy przypadek, że

Metoda 1

var data:[String] = split( featureData ) { $0 == "\u{003B}" }

Kiedy użyłem tego polecenia, aby podzielić jakiś symbol z danych załadowanych z serwera , może się on podzielić podczas testowania w symulatorze i synchronizacji z urządzeniem testowym, ale nie podzieli się w aplikacji publish i Ad Hoc

Śledzenie tego błędu zajmuje mi dużo czasu, może to być jakaś wersja Swift, albo jakaś wersja iOS lub Żadna

Nie chodzi też o kod HTML, ponieważ staram się stringByRemovingPercentEncoding and it ' s still not work

Dodatek 10/10/2015

W Swift 2.0 metoda ta została zmieniona na

var data:[String] = featureData.split {$0 == "\u{003B}"}

Metoda 2

var data:[String] = featureData.componentsSeparatedByString("\u{003B}")

Kiedy użyłem tego polecenia, może podzielić te same dane, które ładują się poprawnie z serwera


Wniosek, naprawdę sugeruję użycie metody 2

string.componentsSeparatedByString("")
 8
Author: Sruit A.Suk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-10 13:21:01

Miałem scenariusz, w którym wiele znaków kontrolnych może być obecnych w łańcuchu, który chcę podzielić. Zamiast utrzymywać ich szereg, po prostu pozwalam Apple zająć się tą częścią.

Poniższe działa z Swift 3.0.1 na iOS 10:

let myArray = myString.components(separatedBy: .controlCharacters)
 8
Author: CodeBender,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-17 20:39:50

Większość z tych odpowiedzi zakłada, że wejście zawiera spację - nie białą i pojedynczą spację. Jeśli można bezpiecznie przyjąć to założenie, to przyjęta odpowiedź (od Bennetta) jest dość elegancka, a także metoda, którą będę się stosował, kiedy będę mógł.

Kiedy nie możemy przyjąć tego założenia, bardziej solidne rozwiązanie musi obejmować następujące siutacje, których większość odpowiedzi tutaj nie bierze pod uwagę:

  • tabs/newlines/spaces (whitespace), w tym powtarzające się znaki
  • początek / koniec spacji
  • Apple / Linux (\n) i Windows (\r\n) znaki nowej linii

Aby pokryć te przypadki, rozwiązanie wykorzystuje regex do konwersji wszystkich białych znaków (w tym powtarzających się i znaków nowej linii systemu Windows) na pojedynczą spację, przycinania, a następnie dzielenia przez pojedynczą spację:

Swift 3:

let searchInput = "  First \r\n \n \t\t\tMiddle    Last "
let searchTerms = searchInput 
    .replacingOccurrences(
        of: "\\s+",
        with: " ",
        options: .regularExpression
    )
    .trimmingCharacters(in: .whitespaces)
    .components(separatedBy: " ")

// searchTerms == ["First", "Middle", "Last"]
 7
Author: DonVaughn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-19 13:42:11

Lub bez zamknięć możesz to zrobić właśnie w Swift 2:

let fullName = "First Last"
let fullNameArr = fullName.characters.split(" ")
let firstName = String(fullNameArr[0])
 6
Author: Rauli Rikama,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-11 04:46:11

Swift 4, Xcode 10 i iOS 12 Aktualizacja 100% działa

let fullName = "First Last"    
let fullNameArr = fullName.components(separatedBy: " ")
let firstName = fullNameArr[0] //First
let lastName = fullnameArr[1] //Last
Więcej informacji można znaleźć w dokumentacji Apple

Tutaj.

 6
Author: Xcodian Solangi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-07 04:46:03

Hope this is helpfull

Swift 4: Podziel ciąg znaków na tablicę. Krok 1: Przypisz ciąg znaków. Krok 2: na podstawie @ spliting. Uwaga: zmienna nazwa.components (separatedBy: "Podziel słowo kluczowe")

let fullName: String = "First Last @ triggerd event of the session by session storage @ it can be divided by the event of the trigger."
let fullNameArr = fullName.components(separatedBy: "@")
print("split", fullNameArr)
 3
Author: Vidhyapathi Kandhasamy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-02 08:35:27

W Swift 4.1 i Xcode 9.4.1

//This is your str
let str = "This is my String" //Here replace with your string

Opcja 1

let items = str.components(separatedBy: " ")//Here replase space with your value and result is Array.
//Direct line of code
//let items = "This is my String".components(separatedBy: " ")
let str1 = items[0]
let str2 = items[1]
let str3 = items[2]
let str4 = items[3]
//OutPut
print(items.count)
print(str1)
print(str2)
print(str3)
print(str4)
print(items.first!)
print(items.last!)

Opcja 2

let items = str.split(separator: " ")
let str1 = String(items.first!)
let str2 = String(items.last!)
//Output
print(items.count)
print(items)
print(str1)
print(str2)

Opcja 3

let arr = str.split {$0 == " "}
print(arr)

Opcja 4

Przez Apple Documentation....

let line = "BLANCHE:   I don't want realism. I want magic!"
print(line.split(separator: " "))
print(line.split(separator: " ", maxSplits: 1))//This can split your string into 2 parts
print(line.split(separator: " ", maxSplits: 2))//This can split your string into 3 parts
print(line.split(separator: " ", omittingEmptySubsequences: false))//array contains empty strings where spaces were repeated.
print(line.split(separator: " ", omittingEmptySubsequences: true))//array not contains empty strings where spaces were repeated.
print(line.split(separator: " ", maxSplits: 4, omittingEmptySubsequences: false))
print(line.split(separator: " ", maxSplits: 3, omittingEmptySubsequences: true))
 3
Author: iOS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-10 13:26:26
let str = "one two"
let strSplit = str.characters.split(" ").map(String.init) // returns ["one", "two"]

Xcode 7.2 (7C68)

 2
Author: Amr Lotfy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-17 15:45:18

Swift 2.2 Error Handling & capitalizedString dodany:

func setFullName(fullName: String) {
    var fullNameComponents = fullName.componentsSeparatedByString(" ")

    self.fname = fullNameComponents.count > 0 ? fullNameComponents[0]: ""
    self.sname = fullNameComponents.count > 1 ? fullNameComponents[1]: ""

    self.fname = self.fname!.capitalizedString
    self.sname = self.sname!.capitalizedString
}
 2
Author: Aqib Mumtaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-02 12:38:19

Załóżmy, że masz zmienną o nazwie "Hello World" i jeśli chcesz ją podzielić i zapisać na dwie różne zmienne, możesz użyć tak:

var fullText = "Hello World"
let firstWord = fullText.text?.components(separatedBy: " ").first
let lastWord = fullText.text?.components(separatedBy: " ").last
 2
Author: Parth Barot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-02 12:55:18

To się zmieniło ponownie w wersji Beta 5. Weee! Jest to teraz metoda Na CollectionType

Stary:

var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}

Nowy:

var fullName = "First Last"
var fullNameArr = fullName.split {$0 == " "}

Apples Release Notes

 1
Author: Daniel H.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-07 20:16:56

Dla swift 2, XCode 7.1:

let complete_string:String = "Hello world"
let string_arr =  complete_string.characters.split {$0 == " "}.map(String.init)
let hello:String = string_arr[0]
let world:String = string_arr[1]
 1
Author: abinop,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-01 06:19:41

Jak Na Swift 2.2

Wystarczy napisać 2-liniowy kod, a otrzymasz rozdzielony ciąg znaków.

let fullName = "FirstName LastName"
var splitedFullName = fullName.componentsSeparatedByString(" ")
print(splitedFullName[0])
print(splitedFullName[1]) 
Smacznego. :)
 1
Author: Gautam Sareriya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-26 14:21:45

Oto algorytm, który właśnie zbudowałem, który podzieli {[2] } przez dowolne Character z tablicy i jeśli istnieje jakaś potrzeba, aby zachować podłańcuchy z rozdzielonymi znakami, można ustawić parametr swallow na true.

Xcode 7.3-Swift 2.2:

extension String {

    func splitBy(characters: [Character], swallow: Bool = false) -> [String] {

        var substring = ""
        var array = [String]()
        var index = 0

        for character in self.characters {

            if let lastCharacter = substring.characters.last {

                // swallow same characters
                if lastCharacter == character {

                    substring.append(character)

                } else {

                    var shouldSplit = false

                    // check if we need to split already
                    for splitCharacter in characters {
                        // slit if the last character is from split characters or the current one
                        if character == splitCharacter || lastCharacter == splitCharacter {

                            shouldSplit = true
                            break
                        }
                    }

                    if shouldSplit {

                        array.append(substring)
                        substring = String(character)

                    } else /* swallow characters that do not equal any of the split characters */ {

                        substring.append(character)
                    }
                }
            } else /* should be the first iteration */ {

                substring.append(character)
            }

            index += 1

            // add last substring to the array
            if index == self.characters.count {

                array.append(substring)
            }
        }

        return array.filter {

            if swallow {

                return true

            } else {

                for splitCharacter in characters {

                    if $0.characters.contains(splitCharacter) {

                        return false
                    }
                }
                return true
            }
        }
    }
}

Przykład:

"test text".splitBy([" "]) // ["test", "text"]
"test++text--".splitBy(["+", "-"], swallow: true) // ["test", "++" "text", "--"]
 1
Author: DevAndArtist,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-09 18:10:39

Obsługa łańcuchów jest wciąż wyzwaniem w języku Swift i zmienia się znacząco, jak widać z innych odpowiedzi. Mam nadzieję, że wszystko się uspokoi i stanie się prostsze. W ten sposób można to zrobić w obecnej wersji Swift 3.0 z wieloma znakami separatora.

Swift 3:

let chars = CharacterSet(charactersIn: ".,; -")
let split = phrase.components(separatedBy: chars)

// Or if the enums do what you want, these are preferred. 
let chars2 = CharacterSet.alphaNumerics // .whitespaces, .punctuation, .capitalizedLetters etc
let split2 = phrase.components(separatedBy: chars2)
 1
Author: possen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-13 19:28:30

Swift 4

let string = "loremipsum.dolorsant.amet:"

let result = string.components(separatedBy: ".")

print(result[0])
print(result[1])
print(result[2])
print("total: \(result.count)")

Wyjście

loremipsum
dolorsant
amet:
total: 3
 1
Author: MrMins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-02 05:32:08

Szukałemluźnego podziału, takiego jak PHP explode gdzie puste sekwencje są zawarte w wynikowej tablicy, to mi się udało:

"First ".split(separator: " ", maxSplits: 1, omittingEmptySubsequences: false)

Wyjście:

["First", ""]
 1
Author: R-Aamir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-18 10:15:10

Nie znalazłem rozwiązania, które obsługiwałoby nazwy z 3 lub więcej komponentów i obsługiwało starsze wersje iOS.

struct NameComponentsSplitter {

    static func split(fullName: String) -> (String?, String?) {
        guard !fullName.isEmpty else {
            return (nil, nil)
        }
        let components = fullName.components(separatedBy: .whitespacesAndNewlines)
        let lastName = components.last
        let firstName = components.dropLast().joined(separator: " ")
        return (firstName.isEmpty ? nil : firstName, lastName)
    }
}

Zaliczone przypadki testowe:

func testThatItHandlesTwoComponents() {
    let (firstName, lastName) = NameComponentsSplitter.split(fullName: "John Smith")
    XCTAssertEqual(firstName, "John")
    XCTAssertEqual(lastName, "Smith")
}

func testThatItHandlesMoreThanTwoComponents() {
    var (firstName, lastName) = NameComponentsSplitter.split(fullName: "John Clark Smith")
    XCTAssertEqual(firstName, "John Clark")
    XCTAssertEqual(lastName, "Smith")

    (firstName, lastName) = NameComponentsSplitter.split(fullName: "John Clark Jr. Smith")
    XCTAssertEqual(firstName, "John Clark Jr.")
    XCTAssertEqual(lastName, "Smith")
}

func testThatItHandlesEmptyInput() {
    let (firstName, lastName) = NameComponentsSplitter.split(fullName: "")
    XCTAssertEqual(firstName, nil)
    XCTAssertEqual(lastName, nil)
}
 0
Author: Vadim Bulavin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-12 09:26:53
var fullName = "James Keagan Michael"
let first = fullName.components(separatedBy: " ").first?.isEmpty == false ? fullName.components(separatedBy: " ").first! : "John"
let last =  fullName.components(separatedBy: " ").last?.isEmpty == false && fullName.components(separatedBy: " ").last != fullName.components(separatedBy: " ").first ? fullName.components(separatedBy: " ").last! : "Doe"
  • Wyklucz to samo imię i nazwisko
  • Jeśli pełna nazwa jest nieprawidłowa, weź wartość zastępczą "John Doe"
 0
Author: jnblanchard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-09 16:38:23