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

时间:2011-11-21 10:30:11

标签: objective-c cocoa

  

可能重复:
  How to count the number of lines in an Objective-C string (NSString)?

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

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

lines = 3;

感谢

3 个答案:

答案 0 :(得分:9)

当心componentsSeparatedByString 不够智能,无法在mac / windows / unix行结尾之间进行检测。在\n上分离将适用于windows / unix行结尾,但不适用于经典的mac文件(并且有一些流行的mac编辑器默认仍然使用这些文件)。您应该检查\r\n\r

加法,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);

答案 1 :(得分:3)

请尝试以下代码。

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

答案 2 :(得分:2)

试试这个

NSString * myString = @"line 1 \n line 2 \n";
int count = [[myString componentsSeparatedByString:@"\n"] count];
NSLog(@"%d", count);