如何截断 NSString?
我查看了字符串格式化文档,但无法弄清楚具体如何执行此操作。
假设我有这样的刺
@"(01–05) 对神经系统的操作"
我想从中创建 2 个字符串,如下所示:
@"01-05"
code> 和 @“神经系统操作”
我该怎么做?
I looked at the string formatting documents but couldn't figure out exactly how to do this.
Lets say I have a sting like this
@"(01–05) Operations on the nervous system"
I want to create 2 strings from this like so:
@"01-05"
and @"Operations on the nervous system"
How can I do this?
Here are the docs I looked at: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/FormatStrings.html
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试一试。可能有点不对劲,我还没检查过是否有错别字。但既然你明白了,你就可以乱搞它了。
Give this a shot. It might be off a bit, I havent checked for typos. But you can mess around with it now that you get the idea.
如果您只想要字符“(”和“)”包含的第一个子字符串以及之后的任何内容,我建议您这样做:
当然,第二部分字符串前面仍然会有空格之类的东西,以获得摆脱那些你可以做一些事情:
使用 NSScanner 的优点是你不必对firstPart子字符串的开始和结束进行硬编码。
If you just want the first substring contained by the characters "(" and ")" and anything after that I'd recommend doing something like this:
Of course the secondPart string will still have spaces and whatnot at the front of it, to get rid of those you can do something along the lines of:
The advantage of using NSScanner is that you don't have to hard-code the start and end of the firstPart substring.
NSString *theFirstStringSubString = [NSString substringFromIndex:1];
NSString *theFirstStringSecondSubstring = [theFirstStringSubString substringToIndex:6];
现在FirstStringSecondSubstring是01-05
另一个是同样的事情,但索引不同。请注意,这些是自动释放的字符串。如果你想保留它们,就保留它。
NSString *theFirstStringSubString = [NSString substringFromIndex:1];
NSString *theFirstStringSecondSubstring = [theFirstStringSubString substringToIndex:6];
Now theFirstStringSecondSubstring is 01-05
same thing for the other but at different indexes. Please note that these are strings that are autoreleased. If you want to keep them, retain it.