views:

709

answers:

2

I want to count the lines in an NSString in Objective-C.

  NSInteger lineNum = 0;
  NSString *string = @"abcde\nfghijk\nlmnopq\nrstu";
  NSInteger length = [string length];
  NSRange range = NSMakeRange(0, length);
  while (range.location < length) {
      range = [string lineRangeForRange:NSMakeRange(range.location, 0)];
      range.location = NSMaxRange(range);
      lineNum += 1;
  }

Is there an easier way?

+3  A: 

well, a not very efficient, but nice(ish) looking way is

NSString *string = @"abcde\nfghijk\nlmnopq\nrstu";
NSInteger length = [[string componentsSeparatedByCharactersInSet:
                                [NSCharacterSet newlineCharacterSet]] count];
cobbal
Thank you ! ! In Above case, how to code?Sorry I'm begginner for Programming
ffffff
Bear in mind that if the string is very long, this will be *much* less efficient than code like what you posted in the question, since it will create a new string object for every line. Be sure you understand how important performance is where you are doing this, and what the upper bound on the string size will be.
smorgan
+3  A: 

Apple recommends this method:

NSString *string;
unsigned numberOfLines, index, stringLength = [string length];

for (index = 0, numberOfLines = 0; index < stringLength; numberOfLines++)
    index = NSMaxRange([string lineRangeForRange:NSMakeRange(index, 0)]);

See the article. They also explain how to count lines of wrapped text.

Loda
In modern code, one should use NSUInteger.
Peter Hosey