Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 704 Vote(s) - 3.52 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Split a String into an array in Swift?

#21
**Swift 4**

let words = "these words will be elements in an array".components(separatedBy: " ")
Reply

#22
## The whitespace issue

Generally, people reinvent this problem and bad solutions over and over. Is this a space? " " and what about "\n", "\t" or some unicode whitespace character that you've never seen, in no small part because it is invisible. While you can get away with

### A weak solution
import Foundation
let pieces = "Mary had little lamb".componentsSeparatedByString(" ")

If you ever need to shake your grip on reality watch a WWDC video on strings or dates. In short, it is almost always better to allow Apple to solve this kind of mundane task.

## Robust Solution: Use NSCharacterSet

The way to do this correctly, IMHO, is to use `NSCharacterSet` since as stated earlier your whitespace might not be what you expect and Apple has provided a whitespace character set. To explore the various provided character sets check out Apple's [NSCharacterSet developer documentation][1] and then, only then, augment or construct a new character set if it doesn't fit your needs.

### NSCharacterSet whitespaces

> Returns a character set containing the characters in Unicode General
> Category Zs and CHARACTER TABULATION (U+0009).

let longerString: String = "This is a test of the character set splitting system"
let components = longerString.components(separatedBy: .whitespaces)
print(components)

[1]:

[To see links please register here]

Reply

#23
var fullName = "James Keagan Michael"
let first = fullName.components(separatedBy: " ").first?.isEmpty == false ? fullName.components(separatedBy: " ").first! : "John"
let last = fullName.components(separatedBy: " ").last?.isEmpty == false && fullName.components(separatedBy: " ").last != fullName.components(separatedBy: " ").first ? fullName.components(separatedBy: " ").last! : "Doe"

- Disallow same first and last name
- If a fullname is invalid, take placeholder value "John Doe"

Reply

#24
I had a scenario where multiple control characters can be present in the string I want to split. Rather than maintain an array of these, I just let Apple handle that part.

The following works with Swift 3.0.1 on iOS 10:

let myArray = myString.components(separatedBy: .controlCharacters)
Reply

#25
Let's say you have a variable named "Hello World" and if you want to split it and store it into two different variables you can use like this:

var fullText = "Hello World"
let firstWord = fullText.text?.components(separatedBy: " ").first
let lastWord = fullText.text?.components(separatedBy: " ").last
Reply

#26
Swift 4 makes it much easier to split characters, just use the new split function for Strings.

Example:
```
let s = "hi, hello"
let a = s.split(separator: ",")
print(a)
```

Now you got an array with 'hi' and ' hello'.
Reply

#27
**Swift 4**

let string = "loremipsum.dolorsant.amet:"

let result = string.components(separatedBy: ".")

print(result[0])
print(result[1])
print(result[2])
print("total: \(result.count)")

**Output**

loremipsum
dolorsant
amet:
total: 3
Reply

#28
I was looking for *loosy* split, such as PHP's `explode` where empty sequences are included in resulting array, this worked for me:

"First ".split(separator: " ", maxSplits: 1, omittingEmptySubsequences: false)

**Output:**

["First", ""]

Reply

#29
You can use this common function and add any string which you want to separate



func separateByString(String wholeString: String, byChar char:String) -> [String] {

let resultArray = wholeString.components(separatedBy: char)
return resultArray
}

var fullName: String = "First Last"
let array = separateByString(String: fullName, byChar: " ")
var firstName: String = array[0]
var lastName: String = array[1]
print(firstName)
print(lastName)
Reply

#30
This is for String and CSV file for swift 4.2 at 20181206 1610


var dataArray : [[String]] = []
let path = Bundle.main.path(forResource: "csvfilename", ofType: "csv")
let url = URL(fileURLWithPath: path!)
do {
let data = try Data(contentsOf: url)
let content = String(data: data, encoding: .utf8)
let parsedCSV = content?.components(separatedBy: "\r\n").map{ $0.components(separatedBy: ";") }
for line in parsedCSV!
{
dataArray.append(line)
}
}
catch let jsonErr {
print("\n Error read CSV file: \n ", jsonErr)
}

print("\n MohNada 20181206 1610 - The final result is \(dataArray) \n ")
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through