如何从Swift中的字符串返回第一个单词?

时间:2016-09-23 18:24:58

标签: swift string swift-playground

如果我们有这样的情况:

 var myString = "Today was a good day"

返回第一个单词的最佳方法是什么,即“今天”?我认为应该应用映射,但不确定如何。

感谢。

5 个答案:

答案 0 :(得分:13)

我能想到的最简单的方法是

Swift 3

let string = "hello world"
let firstWord = string.components(separatedBy: " ").first

Swift 2.2

let string = "hello world"
let firstWord = string.componentsSeparatedByString(" ").first

如果您认为需要在代码中使用它,请将其设为extension

extension String {
    func firstWord() -> String? {
        return self.components(separatedBy: " ").first
    }
}

用法

let string = "hello world"
let firstWord = string.firstWord()

答案 1 :(得分:6)

您可以使用字符串方法enumerateSubstrings和选项.byWords来枚举字符串中的单词并获取第一个元素:

Swift 4.2

import Foundation

extension StringProtocol where Index == String.Index {

    var byLines: [SubSequence] { return components(separated: .byLines) }
    var byWords: [SubSequence] { return components(separated: .byWords) }

    func components(separated options: String.EnumerationOptions)-> [SubSequence] {
        var components: [SubSequence] = []
        enumerateSubstrings(in: startIndex..., options: options) { _, range, _, _ in components.append(self[range]) }
        return components
    }

    var firstWord: SubSequence? {
        var word: SubSequence?
        enumerateSubstrings(in: startIndex..., options: .byWords) { _, range, _, stop in
            word = self[range]
            stop = true
        }
        return word
    }
    var firstLine: SubSequence? {
        var line: SubSequence?
        enumerateSubstrings(in: startIndex..., options: .byLines) { _, range, _, stop in
            line = self[range]
            stop = true
        }
        return line
    }
}

游乐场测试:

let string = "• Today was a good day.\n• Tomorrow will be better.\n"

let firstWord = string.firstWord                               // "Today"
let firstLine = string.firstLine                               // "• Today was a good day."
let firstLineLastWord = string.firstLine?.byWords.last         // day
let firstLineLast2Words = string.firstLine?.byWords.suffix(2)  // ["good", "day"]

答案 2 :(得分:2)

我更喜欢使用CharacterSet,因为单词可以用空格和标点符号分隔。

var myString    = "Today was a good day"
let nonLetters  = CharacterSet.letters.inverted
let first       = myString.components(separatedBy: nonLetters).first

答案 3 :(得分:0)

为避免只为了得到第一个单词就处理整个字符串,可以这样做:

let string = "Hello World"
let word1  = string.prefix{ (c:Character) in CharacterSet.letters.contains(c.unicodeScalars.first!) }

答案 4 :(得分:0)

尝试使用 prefix() 函数

let string = "Today was a good day"
if let spaceIndex = string.firstIndex(of: " ") {
    let firstWord = String(string.prefix(upTo: string.index(after: spaceIndex)))
    print(firstWord)      // Today
}