从NSTextView中提取第一个非空白行的最有效方法是什么?

时间:2011-06-16 23:17:15

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

1 个答案:

答案 0 :(得分:6)

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