本文介绍了如何从 Swift 中的字符串返回第一个单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我们有这样的情况:

If we have, for example, situation like this:

 var myString = "Today was a good day"

返回第一个单词Today"的最佳方式是什么?我认为应该应用映射,但不确定如何应用.

What is the best way to return the first word, which is "Today"? I think mapping should be applied, but not sure how.

谢谢.

推荐答案

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

The simplest way I can think of is

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

斯威夫特 2.2

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

如果您认为需要在代码中大量使用它,请将其作为扩展

and if you think you need to use it a lot in your code, make it as an extension

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

用法

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

这篇关于如何从 Swift 中的字符串返回第一个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:48
查看更多