从 NSTextView 中提取第一个非空白行的最有效方法?
从 NSTextView 中提取第一个非空白行的最有效方法是什么?
例如,如果文本是:
\n
\n
\n
This is the text I want \n
\n
Foo bar \n
\n
结果将是“这是我想要的文本”。
这就是我所拥有的:
NSString *content = self.textView.textStorage.string;
NSInteger len = [content length];
NSInteger i = 0;
// Scan past leading whitespace and newlines
while (i < len && [[NSCharacterSet whitespaceAndNewlineCharacterSet] characterIsMember:[content characterAtIndex:i]]) {
i++;
}
// Now, scan to first newline
while (i < len && ![[NSCharacterSet newlineCharacterSet] characterIsMember:[content characterAtIndex:i]]) {
i++;
}
// Grab the substring up to that newline
NSString *resultWithWhitespace = [content substringToIndex:i];
// Trim leading and trailing whitespace/newlines from the substring
NSString *result = [resultWithWhitespace stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
是否有更好、更有效的方法?
我正在考虑将其放入 -textStorageDidProcessEditing: NSTextStorageDelegate 方法中,以便我可以在编辑文本时获取它。这就是为什么我希望该方法尽可能高效。
What is the most efficient way to pull the first non-whitespace line from an NSTextView?
For example, if the text is:
\n
\n
\n
This is the text I want \n
\n
Foo bar \n
\n
The result would be "This is the text I want".
Here is what I have:
NSString *content = self.textView.textStorage.string;
NSInteger len = [content length];
NSInteger i = 0;
// Scan past leading whitespace and newlines
while (i < len && [[NSCharacterSet whitespaceAndNewlineCharacterSet] characterIsMember:[content characterAtIndex:i]]) {
i++;
}
// Now, scan to first newline
while (i < len && ![[NSCharacterSet newlineCharacterSet] characterIsMember:[content characterAtIndex:i]]) {
i++;
}
// Grab the substring up to that newline
NSString *resultWithWhitespace = [content substringToIndex:i];
// Trim leading and trailing whitespace/newlines from the substring
NSString *result = [resultWithWhitespace stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Is there a better, more efficient way?
I'm thinking of putting this in the -textStorageDidProcessEditing: NSTextStorageDelegate method so I can get it as the text is edited. That's why I'd like the method to be as efficient as possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需使用专为此类事情设计的 NSScanner 即可:
请注意,如果您可以扫描特定字符而不是字符集,速度会快得多:
Just use
NSScanner
which is designed for this sort of thing:Note that it's much faster if you can scan up to a particular character rather than a character set: