Swift split string on first character match

I am trying to make an iOS app in Swift that requires me to split a line of text in the first colon (:) of a line. I tried using the componentsSeparatedByString method in a string, but in addition to the error, indicating that "NSString" does not have a member named "componentSeparatedByString", this method does not actually do what I want.

For a bit more context, I'm trying to separate a line in a game, having the form

<character name> : <line> 

in the name of the character and string. I assume that there is no colon in the character name, so I want to split the first colon in the string so that I don't break the text of the string into parts if there are colons in the text.

So, my first question is: why the use of "componentsSeparatedByString" is not valid in the following code: (the following code does not apply to the situation I mentioned earlier, but this is what I want to fix and save, so I wanted to use it instead colon 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 line along the first colon match (:), and not all matches?

+6
source share
2 answers

first

This is just a typo, not componentSeparatedByString , but componentsSeparatedByString

 let stringArray = contents.componentsSeparatedByString("\n") // ^ 

second

You can use the built-in 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 result type is [String] . If you want [NSString] , just click it:

 let result:[NSString] = split(string as String, { $0 == ":" }, maxSplit: 1, allowEmptySlices: true) // ^^^^^^^^^^^ 
+6
source

Swift 2 answer with split function (for Swift 3, use the maxSplit S parameter, just add "s"):

 let fullString = "ABC" let splittedStringsArray = fullString.characters.split(" ", maxSplit: 1).map(String.init) print(splittedStringsArray) // ["A","BC"] 
+4
source

Source: https://habr.com/ru/post/978815/


All Articles