The most efficient way to pull the first row without spaces from an NSTextView?

What is the most efficient way to pull the first row without spaces from an NSTextView?

For example, if the text:

\n
\n
    \n
         This is the text I want     \n
 \n
Foo bar  \n
\n

The result is "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 am thinking of putting this in the -textStorageDidProcessEditing: NSTextStorageDelegate method so that I can get it when editing text. That is why I would like the method to be as efficient as possible.

+3
source share
1 answer

Just use NSScannerone that is designed for this kind of thing:

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]];

Note that this is much faster if you can scan a specific character, rather than a character set:

[scanner scanUpToString:@"\n" intoString:&output];
+6
source

All Articles