有没有办法计算NSString的行数?

可能重复:
如何计算Objective-C字符串(NSString)中的行数?

有没有办法计算NSString的行数?

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

线= 3;

谢谢


尝试下面的代码。

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

当心componentsSeparatedByString不够智能检测mac / windows / unix行结束。 在n上分离将适用于windows / unix行结尾,但不适用于传统的mac文件(并且有一些流行的mac编辑器仍然默认使用这些文件)。 你应该真的在检查rnr

另外, componentsSeparatedByString:速度慢,内存不足。 如果你关心性能,你应该重复搜索换行符并计算结果数量:

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/85229.html

上一篇: Is there a way to count the number of lines of a NSString ?

下一篇: Check if an NSString is just made out of spaces