Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
779 views
in Technique[技术] by (71.8m points)

ios - Swift split string at first match of a character

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("
")

And my second: How can I split the string along just the first match of the colon (:) character, rather than along all matches?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...