Reputation: 1777
I'm trying to make an iOS app in Swift that requires me to split a line of text at the first colon (:) of a line. I've tried using the the componentsSeparatedByString method on the string, but in addition to getting an error stating "'NSString' does not have a member named 'componentSeparatedByString'", that method doesn't actually do what I want.
For a bit more context, I'm trying to separate a line in a play, that being of the form
<character name> : <line>
into the character's name and the line. I am assuming there is no colon in the character's name, so I want to split at the first colon in the line, so that I won't break the line's text into pieces if there are any colons in the text.
So, my first question: Why isn't the use of 'componentsSeparatedByString' valid in the following code: (the following code isn't the situation I mentioned before, but it's something I want to fix and keep in, so I wanted to use it instead of the colon breaking code.)
var fileRoot = NSBundle.mainBundle().pathForResource("LonelyImpulse", ofType: "txt")
var contents = NSString(contentsOfFile:fileRoot!, encoding: NSUTF8StringEncoding, error: nil)!
let stringArray = contents.componentSeparatedByString("\n")
And my second: How can I split the string along just the first match of the colon (:) character, rather than along all matches?
Upvotes: 17
Views: 13944
Reputation: 11073
Swift 4.2, Swift 5 answer:
let str = "Hello, this is, a, playground"
let splitStringArray = str.split(separator: ",", maxSplits: 1).map(String.init)
print(splitStringArray) // ["Hello", " this is, a, playground"]
Upvotes: 12
Reputation: 756
Swift 2 answer with split function(for Swift 3 use maxSplitS parameter, just add "s"):
let fullString = "A B C"
let splittedStringsArray = fullString.characters.split(" ", maxSplit: 1).map(String.init)
print(splittedStringsArray) // ["A","B C"]
Upvotes: 10
Reputation: 51911
the first
It's just a typo, not componentSeparatedByString
, but componentsSeparatedByString
let stringArray = contents.componentsSeparatedByString("\n")
// ^
the second
You can use builtin split
function which can specify maxSplit
:
let str:NSString = "test:foo:bar"
let result = split(str as String, { $0 == ":" }, maxSplit: 1, allowEmptySlices: true)
// -> ["test", "foo:bar"]
Note that the type of the result is [String]
. If you want [NSString]
, just cast it:
let result:[NSString] = split(string as String, { $0 == ":" }, maxSplit: 1, allowEmptySlices: true)
// ^^^^^^^^^^^
Upvotes: 7