import Foundationlet 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]
对于Swift 3:
import Foundation
let fullName : String = "First Last"let fullNameArr : [String] = fullName.components(separatedBy: " ")
// And then to access the individual words:
var firstName : String = fullNameArr[0]var lastName : String = fullNameArr[1]
import Foundation
var fullName: String = "First Last"let fullNameArr = fullName.componentsSeparatedByString(" ")
var firstName: String = fullNameArr[0]var lastName: String = fullNameArr[1]
Swift 3+更新
import Foundation
let fullName = "First Last"let fullNameArr = fullName.components(separatedBy: " ")
let name = fullNameArr[0]let surname = fullNameArr[1]
// iOS (9.0 and later), macOS (10.11 and later), tvOS (9.0 and later), watchOS (2.0 and later)let nameFormatter = PersonNameComponentsFormatter()
let name = "Mr. Steven Paul Jobs Jr."// personNameComponents requires iOS (10.0 and later)if let nameComps = nameFormatter.personNameComponents(from: name) {nameComps.namePrefix // Mr.nameComps.givenName // StevennameComps.middleName // PaulnameComps.familyName // JobsnameComps.nameSuffix // Jr.
// It can also be configured to format your names// Default (same as medium), short, long or abbreviated
nameFormatter.style = .defaultnameFormatter.string(from: nameComps) // "Steven Jobs"
nameFormatter.style = .shortnameFormatter.string(from: nameComps) // "Steven"
nameFormatter.style = .longnameFormatter.string(from: nameComps) // "Mr. Steven Paul Jobs jr."
nameFormatter.style = .abbreviatednameFormatter.string(from: nameComps) // SJ
// It can also be use to return an attributed string using annotatedString methodnameFormatter.style = .longnameFormatter.annotatedString(from: nameComps) // "Mr. Steven Paul Jobs jr."}
let longerString: String = "This is a test of the character set splitting system"let components = longerString.components(separatedBy: .whitespaces)print(components)
extension String {
func splitBy(characters: [Character], swallow: Bool = false) -> [String] {
var substring = ""var array = [String]()var index = 0
for character in self.characters {
if let lastCharacter = substring.characters.last {
// swallow same charactersif lastCharacter == character {
substring.append(character)
} else {
var shouldSplit = false
// check if we need to split alreadyfor splitCharacter in characters {// slit if the last character is from split characters or the current oneif character == splitCharacter || lastCharacter == splitCharacter {
shouldSplit = truebreak}}
if shouldSplit {
array.append(substring)substring = String(character)
} else /* swallow characters that do not equal any of the split characters */ {
substring.append(character)}}} else /* should be the first iteration */ {
substring.append(character)}
index += 1
// add last substring to the arrayif index == self.characters.count {
array.append(substring)}}
return array.filter {
if swallow {
return true
} else {
for splitCharacter in characters {
if $0.characters.contains(splitCharacter) {
return false}}return true}}}}
let fullName = "First Last"var fullNameArr = fullName.components(separatedBy: " ")
var firstname = fullNameArr[0] // Firstvar lastname = fullNameArr[1] // Last
长途跋涉:
var fullName: String = "First Last"fullName += " " // this will help to see the last word
var newElement = "" //Empty Stringvar fullNameArr = [String]() //Empty Array
for Character in fullName.characters {if Character == " " {fullNameArr.append(newElement)newElement = ""} else {newElement += "\(Character)"}}
var firsName = fullNameArr[0] // Firstvar lastName = fullNameArr[1] // Last
let chars = CharacterSet(charactersIn: ".,; -")let split = phrase.components(separatedBy: chars)
// Or if the enums do what you want, these are preferred.let chars2 = CharacterSet.alphaNumerics // .whitespaces, .punctuation, .capitalizedLetters etclet split2 = phrase.components(separatedBy: chars2)
let fullName: String = "First Last @ triggerd event of the session by session storage @ it can be divided by the event of the trigger."let fullNameArr = fullName.components(separatedBy: "@")print("split", fullNameArr)
let string = "loremipsum.dolorsant.amet:"
let result = string.components(separatedBy: ".")
print(result[0])print(result[1])print(result[2])print("total: \(result.count)")
//This is your strlet str = "This is my String" //Here replace with your string
备选案文1
let items = str.components(separatedBy: " ")//Here replase space with your value and the result is Array.//Direct single line of code//let items = "This is my String".components(separatedBy: " ")let str1 = items[0]let str2 = items[1]let str3 = items[2]let str4 = items[3]//OutPutprint(items.count)print(str1)print(str2)print(str3)print(str4)print(items.first!)print(items.last!)
let line = "BLANCHE: I don't want realism. I want magic!"print(line.split(separator: " "))// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
let line = "BLANCHE: I don't want realism. I want magic!"print(line.split(separator: " "))// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
print(line.split(separator: " ", maxSplits: 1))//This can split your string into 2 parts// Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
print(line.split(separator: " ", maxSplits: 2))//This can split your string into 3 parts
print(line.split(separator: " ", omittingEmptySubsequences: false))//array contains empty strings where spaces were repeated.// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
print(line.split(separator: " ", omittingEmptySubsequences: true))//array not contains empty strings where spaces were repeated.print(line.split(separator: " ", maxSplits: 4, omittingEmptySubsequences: false))print(line.split(separator: " ", maxSplits: 3, omittingEmptySubsequences: true))
let paragraph = "Bob hit a ball, the hit BALL flew far after it was hit. Hello! Hie, How r u?"
let words = paragraph.components(separatedBy: [",", " ", "!",".","?"])
// TESTINGlet str1 = "Hello user! What user's details? Here user rounded with space."let a = str1.split(withSubstring: "user") // <-------------- HERE IS A SPLITprint(a) // ["Hello ", "! What ", "\'s details? Here ", " rounded with space."]
// testing the resultvar result = ""for item in a {if !result.isEmpty {result += "user"}result += item}print(str1) // "Hello user! What user's details? Here user rounded with space."print(result) // "Hello user! What user's details? Here user rounded with space."print(result == str1) // true
/// Extension providing `split` and `substring` methods.extension String {
/// Split given string with substring into array/// - Parameters:/// - string: the string/// - substring: the substring to search/// - Returns: array of componentsfunc split(withSubstring substring: String) -> [String] {var a = [String]()var str = selfwhile let range = str.range(of: substring) {let i = str.distance(from: str.startIndex, to: range.lowerBound)let j = str.distance(from: str.startIndex, to: range.upperBound)let left = str.substring(index: 0, length: i)let right = str.substring(index: j, length: str.length - j)a.append(left)str = right}if !str.isEmpty {a.append(str)}return a}
/// the length of the stringpublic var length: Int {return self.count}
/// Get substring, e.g. "ABCDE".substring(index: 2, length: 3) -> "CDE"////// - parameter index: the start index/// - parameter length: the length of the substring////// - returns: the substringpublic func substring(index: Int, length: Int) -> String {if self.length <= index {return ""}let leftIndex = self.index(self.startIndex, offsetBy: index)if self.length <= index + length {return String(self[leftIndex..<self.endIndex])}let rightIndex = self.index(self.endIndex, offsetBy: -(self.length - index - length))return String(self[leftIndex..<rightIndex])}
}