1

I have a string like

 NSString * aString = @"\n    \n    \n   This is my string  ";

I need to extract firs blank spaces and new line characters upto first non-whitespace non-newline character. that is the output should be

NSString *output = @"\n    \n    \n   ";

I tried it with NSScanner as follows NSString * aString = @"\n \n \n This is my string ";

NSScanner *scanner = [NSScanner scannerWithString:aString];
NSCharacterSet *characterSet = [[NSCharacterSet whitespaceAndNewlineCharacterSet] invertedSet];
NSString *output = nil;
[scanner scanUpToCharactersFromSet:characterSet intoString:&output];

But after execution the output string is nil. whats wrong with this code?

Johnykutty
  • 12,091
  • 13
  • 59
  • 100

1 Answers1

2

You can use regular expression to match all whitespaces (\s*) in the begining of the line (^):

NSString *string = @"\n    \n    \n   This is my string  ";
NSRegularExpression *expression = [[NSRegularExpression alloc] initWithPattern:@"^\\s*" options:0 error:NULL];
NSTextCheckingResult *match = [expression firstMatchInString:string options:0 range:NSMakeRange(0, string.length)];
NSString *output = [string substringWithRange:match.range];
ksysu
  • 311
  • 4
  • 6
  • Ok.. its working perfectly. Thank you for answer. Btw do you have any idea about what the problem with my NSScanner implementation? – Johnykutty Sep 02 '14 at 07:11
  • Also what I need to do for finding same from end of the striog? – Johnykutty Sep 02 '14 at 07:13
  • 1
    I tried to do something with your scanner, but I have no idea what is wrong there. You can use @"\\s*$" for finding same at the end ($ stands for end) – ksysu Sep 02 '14 at 07:36