Swift split string at first match of a character

swift split string into characters
swift string split
swift string to character
swift separate string to array
split string after swift
swift string character at index
swift substring to character
string separation in swift

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 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)
//        ^^^^^^^^^^^

ios - Swift split string at first match of a character, componentSeparatedByString("\n"). And my second: How can I split the string along just the first match of the colon (:) character, rather than  A string has multiple parts separated by special characters (delimiter characters). We can separate these parts into a String array. In Swift, there is no special split method. But we invoke components(), part of the Foundation library, with a separatedBy argument.

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"]

Swift split string at first match of a character, 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? So by the end of this tutorial you should be able to get the first few characters from the start or the end of a string in either Swift 3 or 4. NOTE: This tutorial was created using a Xcode 9.2 Playground and assumes you have at least Swift 4.0 installed in your Xcode toolchain or that you are using a version of Xcode that supports Swift 4, such as Xcode 9.

Swift 4.2 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"]

split(separator:maxSplits:omittingEmptySubsequences:), Swift Standard Library func split(separator: Character, maxSplits: Int = Int.max, in the collection and for each instance of separator at the start or end of the  Utilizing the contains instance method from the String class, out of Foundation, will return true if a range of a string is contained within another string. As an example, if a parent string was iterated through like a collection of characters and then a range of a substring was checked for at each character in the parent string, this could be a conceptual example of how finding a substring

Swift split string at first match of a character - ios, 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 first one creates an NSRange encompassing our entire string, and the second looks for the first match in our test string. This is clumsy: most of the time you’re going to want to search the entire input string, and using firstMatch(in:) along with a nil check really muddies your intent.

How to Split a String, I did not want each character to change, but rather I wanted each word to be altered in the same way during each iteration (move the first letter of  Strings and Characters¶ A string is a series of characters, such as "hello, world" or "albatross". Swift strings are represented by the String type. The contents of a String can be accessed in various ways, including as a collection of Character values. Swift’s String and Character types provide a fast, Unicode-compliant way to work with text in your code.

Strings and Characters, Use a string literal as an initial value for a constant or variable: If you need the special effects of a character in a string literal, match the number of When you get a substring from a string—for example, using a subscript or a method like  A String is now a collection of characters by default so iterating over a String or Substring gives you each character in the `String: // Swift 4 for character in country { print (character) } To get the first or last character in a String. The result is an optional returning nil if the String is empty.

Comments
  • I strongly recommend using split, there is a nasty problem when using componentsSeparatedByString on Swift 1.2.
  • @MauryMarkowitz, what is the nasty problem?
  • @Suragch I don't recall exactly, but it was a bridging problem that caused nonsense errors. I only debugged it by changing another line of code and noticing it didn't crash although it was ostensibly doing the same thing.
  • How would you modernize the second function for swift 3?
  • The docs for the maxSplits option read: Returns the longest possible subsequences of the collection, in order, around elements equal to the given element. (developer.apple.com/documentation/swift/string/2894564-split). The longest possible phrase seems odd to me. No matter what I try, with split = 1, it always splits at the first occurrence of the separator.