Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string in Swift [duplicate]

let string = "hello hi" var hello = "" var hi = "" 

I wan't to split my string so that the value of hello get "hello" and the value of hi get "hi"

like image 501
Clément Bisaillon Avatar asked Sep 12 '14 23:09

Clément Bisaillon


People also ask

How do I split a string in Swift?

Swift String split() The split() method breaks up a string at the specified separator and returns an array of strings.

How do I remove a character from a string in Swift?

Null Character ( \0 )

How do I remove spaces from a string in Swift?

To remove all leading whitespaces, use the following code: var filtered = "" var isLeading = true for character in string { if character. isWhitespace && isLeading { continue } else { isLeading = false filtered.

How do I convert a string to an array in Swift?

To split a string to an array in Swift by a character, use the String. split(separator:) function. However, this requires that the separator is a singular character, not a string.


2 Answers

Try this:

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

Where myString is the name of your string, and myStringArr contains the components separated by the space.

Then you can get the components as:

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

Doc: componentsSeparatedByString

EDIT: For Swift 3, the above will be:

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

Doc: components(separatedBy:)

like image 175
JosEduSol Avatar answered Sep 28 '22 06:09

JosEduSol


Here are split that receives regex as well. You can define extension for future usage:

Swift 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)     } } 

Examples:

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

Swift 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)     } } 

Swift 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 []         }     } } 

Swift 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)     } } 

Examples:

let string1 = "hello world"  string1.split(" ")    // ["hello", "world"]  let string2 = "hello    world"  string2.split("[ ]+")  // ["hello", "world"] 
like image 32
Maxim Shoustin Avatar answered Sep 28 '22 04:09

Maxim Shoustin