Cocoa 从NSTextView中提取第一条非空白行的最有效方法?
从NSTextView中提取第一条非空白行的最有效方法是什么 例如,如果文本为:Cocoa 从NSTextView中提取第一条非空白行的最有效方法?,cocoa,nsstring,nstextview,Cocoa,Nsstring,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; // Sc
\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]];
NSString*content=self.textView.textStorage.string;
NSInteger len=[内容长度];
NSInteger i=0;
//扫描前导空格和换行符
而(i
有没有更好、更有效的方法
我正在考虑将其放入-textStorageDidProcessEditing:NSTextStorageDelegate方法中,以便在编辑文本时获得它。这就是我希望该方法尽可能高效的原因。只需使用专为此类事情设计的
NSScanner
:
NSString* output = nil;
NSScanner* scanner = [NSScanner scannerWithString:yourString];
[scanner scanCharactersFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet] intoString:NULL];
[scanner scanUpToCharactersFromSet:[NSCharacterSet newlineCharacterSet] intoString:&output];
output = [output stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
请注意,如果可以最多扫描一个特定字符而不是一个字符集,则速度会快得多:
[scanner scanUpToString:@"\n" intoString:&output];
谢谢你,罗伯。这很整洁。这比逐字逐句快吗?每次编辑textview时创建NSScanner对象的成本高吗?
NSScanner
经过高度优化,肯定比您的代码快。对象创建开销太小,不必担心。它是否足够快取决于文本视图中实际有多少文本。为什么不分析这两种方法并亲自看看哪一种更快?在性能方面,我使用NSScanner
对NSTextView
的内容运行多次遍历,在文本中每次更改时搜索各种标记,以实现语法着色。这绝对够快的了。谢谢你的跟进,罗伯。非常有用。