I read from a csv file, and want to split the long string that I get using stringWithContentsOfFile, which is a multi line string, with individual lines representing rows in the csv file. How do I do this?
相关问题
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
- “Zero out” sensitive String data in Swift
- Get the NSRange for the visible text after scroll
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- Swift - hide pickerView after value selected
- How do you detect key up / key down events from a
- didBeginContact:(SKPhysicsContact *)contact not in
- Attempt to present UIAlertController on View Contr
You can break the string into arrays of string and then manipulate as you want.
Here's my take on it:
Running this prints:
It may not be the most efficient way (probably using an
NSScanner
would be faster), but it solves the problem here.Swift 3 version:
Nice and short.
You should be aware that
\n
is not the only character used to split a new line. For example, if the file was saved in Windows, the newline characters would be\r\n
. Read the Newline article in Wikipedia for more information about this.Thus, if you just use
componentsSeparatedByString("\n")
, you may get unexpected results.Note both the residual
\r
and the empty array element.There are several ways to avoid these problems.
Solutions
1.
componentsSeparatedByCharactersInSet
If
filter
were not used, then\r\n
would produce an empty array element because it gets counted as two characters and so separates the string twice at the same location.2.
split
or
Here
\r\n
gets counted as a single Swift character (an extended grapheme cluster)3.
enumerateLines
For more about the
enumerateLine
syntax, see this answer also.Notes:
\r\n
and\n
but I am doing this here to show that these methods can handle both formats.NSCharacterSet.newlineCharacterSet()
are newline characters defined as (U+000A–U+000D, U+0085), which include\r
and\n
.Just in case anyone stumbles across this question like I did. This will work with any newline characters:
You need to separate your content with "\n".