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

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


尝试下面的代码。

NSString * myString = @"line 1 n line 2 n";
NSArray *list = [myString componentsSeparatedByString:@"n"];
NSLog(@"No of lines : %d",[list count]);

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 rn 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);

尝试这个

NSString * myString = @"line 1 n line 2 n";
int count = [[myString componentsSeparatedByString:@"n"] count];
NSLog(@"%d", count);
链接地址: http://www.djcxy.com/p/85230.html

上一篇: 从NSString中提取数字

下一篇: 有没有办法计算NSString的行数?