1

Possible Duplicate:
How to count the number of lines in an Objective-C string (NSString)?

Is there a way to count the number of lines of a NSString ?

NSString * myString = @"line 1 \n line 2 \n";

lines = 3;

thanks

Community
  • 1
  • 1
aneuryzm
  • 63,052
  • 100
  • 273
  • 488
  • @Patrick please search on SO and google before posting question on SO. – Parag Bafna Nov 21 '11 at 11:02
  • You should Refer Text Layout Programming Guide. [Counting Lines of Text](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/TextLayout/Tasks/CountLines.html) – Parag Bafna Nov 21 '11 at 11:01

3 Answers3

9

Beware componentsSeparatedByString is not smart enough to detect between mac/windows/unix line endings. Separating on \n will work for windows/unix line endings, but not classic mac files (and there are some popular mac editors which still use these by default). You should really be checking for \r\n and \r.

Is addition, componentsSeparatedByString: is slow and memory hungry. If you care about performance, you should repeatedly search for newlines and count the number of results:

NSString * myString = @"line 1 \n line 2 \n";

int lineCount = 1;
NSUInteger characterLocation = 0;
NSCharacterSet *newlineCharacterSet = [NSCharacterSet newlineCharacterSet];
while (characterLocation < myString.length) {
  characterLocation = [myString rangeOfCharacterFromSet:newlineCharacterSet options:NSLiteralSearch range:NSMakeRange(characterLocation, (myString.length - characterLocation))].location;

  if (characterLocation == NSNotFound) {
    break;
  }

  // if we are at a \r character and the next character is a \n, skip the next character
  if (myString.length >= characterLocation &&
      [myString characterAtIndex:characterLocation] == '\r' &&
      [myString characterAtIndex:characterLocation + 1] == '\n') {
    characterLocation++;
  }

  lineCount++;
  characterLocation++;
}

NSLog(@"%i", lineCount);
Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110
  • 1
    The latter solution will also correctly handle CRLF sequences, whereas `componentsSeparatedByCharactersInSet:` will return an empty component for each such sequence. – Peter Hosey Nov 21 '11 at 15:07
  • Thanks @PeterHosey I thought the exact opposite of what you're saying is true, but I did some tests and you're right. My code was broken on windows newlines. I have edited my answer to delete the one-line example, and updated the long/fast example to check for `\r\n`. – Abhi Beckert Nov 21 '11 at 21:28
3

Try the following code.

NSString * myString = @"line 1 \n line 2 \n";
NSArray *list = [myString componentsSeparatedByString:@"\n"];
NSLog(@"No of lines : %d",[list count]);
Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55
2

Try this

NSString * myString = @"line 1 \n line 2 \n";
int count = [[myString componentsSeparatedByString:@"\n"] count];
NSLog(@"%d", count);
beryllium
  • 29,669
  • 15
  • 106
  • 125