【问题标题】:How to split a string in Swift [duplicate]如何在 Swift 中拆分字符串 [重复]
【发布时间】:2014-11-07 05:13:33
【问题描述】:
let string = "hello hi"
var hello = ""
var hi = ""

我不想拆分我的字符串,以便 hello 的值得到“hello”,hi 的值得到“hi”

【问题讨论】:

    标签: string swift split


    【解决方案1】:

    这里是split,它也接收正则表达式。您可以定义扩展以供将来使用:

    斯威夫特 4

    extension String {
    
        func split(regex pattern: String) -> [String] {
    
            guard let re = try? NSRegularExpression(pattern: pattern, options: [])
                else { return [] }
    
            let nsString = self as NSString // needed for range compatibility
            let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
            let modifiedString = re.stringByReplacingMatches(
                in: self,
                options: [],
                range: NSRange(location: 0, length: nsString.length),
                withTemplate: stop)
            return modifiedString.components(separatedBy: stop)
        }
    }
    

    例子:

    let string1 = "hello world"
    string1.split(regex: " ")    // ["hello", "world"]
    
    let string2 = "hello    world"
    string2.split(regex: "[ ]+")  // ["hello", "world"]
    

    斯威夫特 2.2

    extension String {
    
        func split(regex pattern: String) -> [String] {
    
            guard let re = try? NSRegularExpression(pattern: pattern, options: []) 
                else { return [] }
    
            let nsString = self as NSString // needed for range compatibility
            let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
            let modifiedString = re.stringByReplacingMatchesInString(
                self,
                options: [],
                range: NSRange(location: 0, length: nsString.length),
                withTemplate: stop)
            return modifiedString.componentsSeparatedByString(stop)
        }
    }
    

    斯威夫特 2.0

    extension String {
    
        // java, javascript, PHP use 'split' name, why not in Swift? :)
        func split(regex: String) -> Array<String> {
            do{
                let regEx = try NSRegularExpression(pattern: regex, options: NSRegularExpressionOptions())
                let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
                let nsString = self as NSString // needed for range compatibility
                let modifiedString = regEx.stringByReplacingMatchesInString (self, options: NSMatchingOptions(), range: NSRange(location: 0, length: nsString.length), withTemplate:stop)
                return modifiedString.componentsSeparatedByString(stop)
            } catch {
                return []
            }
        }
    }
    

    斯威夫特 1.1

    extension String {
    
        // java, javascript, PHP use 'split' name, why not in Swift? :)
        func split(splitter: String) -> Array<String> {
            let regEx = NSRegularExpression(pattern: splitter, options: NSRegularExpressionOptions(), error: nil)
            let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
            let modifiedString = regEx.stringByReplacingMatchesInString (self, options: NSMatchingOptions(),
                range: NSMakeRange(0, countElements(self)),
                withTemplate:stop)
            return modifiedString.componentsSeparatedByString(stop)
        }
    }
    

    例子:

    let string1 = "hello world"
    
    string1.split(" ")    // ["hello", "world"]
    
    let string2 = "hello    world"
    
    string2.split("[ ]+")  // ["hello", "world"]
    

    【讨论】:

    • @downvoter 请描述
    • 我没有投反对票。我知道该方法的缺点:您不知道参数何时是纯字符串而何时是正则表达式模式字符串。例如,如果我想用 "\d+" (文字字符串,而不是正则表达式)分割一个字符串
    • @TylerLong 该方法告诉您它是一个正则表达式。如果你想用文字 "\d+" 分割,那么你传入一个描述该文字字符串的正则表达式。例如:"\\\\d\\+"
    • 我建议将方法重命名为func split(regex pattern: String) -&gt; [String],所以在调用站点上它是string1.split(regex: " ")。 (“模式”,因为regex 应该是NSRegularExpression)现有的CollectionType.split 也可以采用单个字符,因此当参数为" " 时很难判断调用的是哪个。跨度>
    【解决方案2】:

    试试这个:

    var myString: String = "hello hi";
    var myStringArr = myString.componentsSeparatedByString(" ")
    

    myString 是字符串的名称,myStringArr 包含由空格分隔的组件。

    然后你可以得到组件为:

    var hello: String = myStringArr [0]
    var hi: String = myStringArr [1]
    

    文档:componentsSeparatedByString

    编辑:对于 Swift 3,上面将是:

    var myStringArr = myString.components(separatedBy: " ")
    

    文档:components(separatedBy:)

    【讨论】:

    • 很好的答案。最简单的方法
    • 上述在 Swift 3 中有所改变,现在是:'var arrayOfSeperatedParts = myOriginalString.components(separatedBy: "insertSeperatorHere")'
    猜你喜欢
    • 2020-04-04
    • 2010-12-02
    • 2023-03-17
    • 2015-05-29
    • 2012-09-18
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多