cocoa - 从 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;

// 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 方法中,以便我可以在编辑文本时获取它。这就是为什么我希望该方法尽可能高效。

最佳答案

只需使用专为此类事情设计的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];

关于cocoa - 从 NSTextView 中提取第一个非空白行的最有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6379715/

相关文章:

objective-c - NSTextView 的意外行为(因为没有标题栏的 NSWindow?)

objective-c - 返回 NSTextView 的选择属性

multithreading - 我的 cocoa 应用程序记录了一些 "[Switching to process XXXX thread 0xXXXX]"

cocoa - 使用 @sum 等集合运算符进行 NSTableColumn 绑定(bind)

objective-c - Objective-C 上下文中不熟悉的 C 语法

objective-c - 如何使用 NSTextStorage 配置 NSTextView?

macos - Mac OS X - 监控应用程序启动?

iphone - 获取歌词 iPhone

objective-c - 有没有办法获取另一个 NSString 中出现的 NSString 的 NSRanges 的 NSArray?

ios - 如何在后台将一个 iOS 应用程序的 NSString 对象的值更改为另一个 iOS 应用程序?