Swift在一个角色的第一场比赛中分裂字符串 [英] Swift split string at first match of a character
问题描述
我正在尝试在Swift中创建一个iOS应用程序,它要求我在一行的第一个冒号(:)中拆分一行文本。我已经尝试在字符串上使用componentsSeparatedByString方法,但除了收到错误声明'NSString'没有名为'componentSeparatedByString'的成员之外,该方法实际上并没有按我的意愿行事。
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.
所以,我的第一个问题:为什么不使用'componentsSeparatedByString'在以下代码中有效:(以下代码不是我之前提到的情况,但它是我的东西想要修复并保留,所以我想使用它而不是冒号破坏代码。)
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?
推荐答案
第一个
这只是一个错字,而不是 componentSeparatedByString
,但 componentsSeparatedByString
It's just a typo, not componentSeparatedByString
, but componentsSeparatedByString
let stringArray = contents.componentsSeparatedByString("\n")
// ^
第二个
您可以使用内置拆分
函数,该函数可以指定 maxSplit
:
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"]
请注意,结果的类型是 [字符串]
。如果你想 [NSString]
,只需投出它:
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)
// ^^^^^^^^^^^
这篇关于Swift在一个角色的第一场比赛中分裂字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!