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?
The String. split() Function. To split a string into an array in Swift, use the String. split() function.
Swift String split() The split() method breaks up a string at the specified separator and returns an array of strings.
To convert a string to an array, we can use the Array() intializer syntax in Swift. Here is an example, that splits the following string into an array of individual characters. Similarly, we can also use the map() function to convert it. The map() function iterates each character in a string.
Swift – String Length/Count To get the length of a String in Swift, use count property of the string. count property is an integer value representing the number of characters in this string.
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"]
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)
// ^^^^^^^^^^^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With