通过空行将 NSString 拆分为 NSArray
我正在将 *.srt 字幕文件读入 NSString 中。该字符串的内容如下所示:
1
00:00:20,000 --> 00:00:24,400
Altocumulus clouds occur between six thousand
2
00:00:24,600 --> 00:00:27,800
and twenty thousand feet above ground level.
我正在寻找一种优雅的解决方案来将该字符串拆分为 NSArray,其中每个元素都包含与一个特定字幕“frame”相关的信息,例如第零个元素如下所示:
1
00:00:20,000 --> 00:00:24,400
Altocumulus clouds occur between six thousand
有什么想法可以优雅地完成这项任务吗?我尝试使用该方法拆分原始字符串
[string componentsSeparatedByString:@"\n\n"];
,但该方法无法检测空行..
感谢您的帮助!
托比
I am reading a *.srt subtitle file into a NSString. The content of this string looks like this:
1
00:00:20,000 --> 00:00:24,400
Altocumulus clouds occur between six thousand
2
00:00:24,600 --> 00:00:27,800
and twenty thousand feet above ground level.
I am looking for an elegant solution to split this string into an NSArray in which each element contains the information which is related to one particular subtitle-"frame", e.g. the zeroth element would look like this:
1
00:00:20,000 --> 00:00:24,400
Altocumulus clouds occur between six thousand
Any ideas how to accomplish this task in an elegant manner? I tried splitting the original string using the method
[string componentsSeparatedByString:@"\n\n"];
but this method fails to detect the blank lines..
Thanks for your help!
tobi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果
[string ComponentsSeparatedByString:@"\n\n"]
不起作用,则有两种可能:您的文件包含 MSDOS 样式的换行符,即
\r \n
。因此,请尝试在@"\r\n\r\n"
上进行拆分。您所谓的空白行包含空格或制表符。您可以使用
cat -e
从 shell 进行检查。If
[string componentsSeparatedByString:@"\n\n"]
doesn't work, then there are two possibilities:Your file contains MSDOS-style line breaks, which are
\r\n
. So try splitting on@"\r\n\r\n"
.Your supposedly blank lines contain spaces or tabs. You can check this from the shell using
cat -e
.我建议使用
NSScanner
代替。它更加灵活,您不必担心换行符是 Windows 还是 Unix 样式以及空行是否包含空格。这是一个例子:I'd suggest using
NSScanner
instead. It's more flexible and you don't have to worry about whether your line breaks are Windows or Unix style and whether the blank lines contain any spaces. Here's an example:根据 http://en.wikipedia.org/wiki/SubRip,换行符是CRLF,即
\r\n
。According to http://en.wikipedia.org/wiki/SubRip, the line breaks are a CRLF, which would be
\r\n
.