在Swift中将字符串拆分成数组?

本文翻译自:Split a String into an array in Swift?

Say I have a string here: 说我在这里有一个字符串:

var fullName: String = "First Last"

I want to split the string base on white space and assign the values to their respective variables 我想在空白处分割字符串并将值分配给它们各自的变量

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

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

Also, sometimes users might not have a last name. 同样,有时用户可能没有姓氏。


#1楼

参考:https://stackoom.com/question/1jk7J/在Swift中将字符串拆分成数组


#2楼

The easiest method to do this is by using componentsSeparatedBy: 最简单的方法是使用componentsSeparatedBy:

For Swift 2: 对于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]

For Swift 3: 对于Swift 3:

import Foundation

let fullName : String &#
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值