Swift split string at first match of a character

前端 未结 3 1616
粉色の甜心
粉色の甜心 2020-12-20 15:37

I\'m trying to make an iOS app in Swift that requires me to split a line of text at the first colon (:) of a line. I\'ve tried using the the componentsSeparatedByString meth

相关标签:
3条回答
  • 2020-12-20 15:47

    Swift 4.2, Swift 5 answer:

    let str = "Hello, this is, a,  playground"
    let splitStringArray = str.split(separator: ",", maxSplits: 1).map(String.init)
    
    print(splitStringArray) // ["Hello", " this is, a,  playground"]
    
    0 讨论(0)
  • 2020-12-20 15:55

    the first

    It's just a typo, not componentSeparatedByString, but componentsSeparatedByString

    let stringArray = contents.componentsSeparatedByString("\n")
    //                                  ^ 
    

    the second

    You can use builtin split function which can specify maxSplit:

    let str:NSString = "test:foo:bar"
    let result = split(str as String, { $0 == ":" }, maxSplit: 1, allowEmptySlices: true)
    // -> ["test", "foo:bar"]
    

    Note that the type of the result is [String]. If you want [NSString], just cast it:

    let result:[NSString] = split(string as String, { $0 == ":" }, maxSplit: 1, allowEmptySlices: true)
    //        ^^^^^^^^^^^
    
    0 讨论(0)
  • 2020-12-20 16:06

    Swift 2 answer with split function(for Swift 3 use maxSplitS parameter, just add "s"):

    let fullString = "A B C"
    let splittedStringsArray = fullString.characters.split(" ", maxSplit: 1).map(String.init)
    print(splittedStringsArray) // ["A","B C"]
    
    0 讨论(0)
提交回复
热议问题