objective-c - 有没有办法计算 NSString 的行数?

标签 objective-c cocoa

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

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

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

行数 = 3;

谢谢

最佳答案

注意 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);

关于objective-c - 有没有办法计算 NSString 的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8210364/

相关文章:

iphone - CLLocation 导致 EXC_BAD_ACCESS

objective-c - 为什么我可以在 NSWindowController 中实现 NSDraggingDestination 方法?

objective-c - 从 ViewController Cocoa Mac Storyboard Xcode 6 以外的其他类触发的工作表模态警报

cocoa - NSMenuItem 数字气泡?

Objective-C 和 Cocoa : crash when calling a class function without entering the function

ios - setNeedsDisplay 不调用 drawRect

objective-c - Objective C - 通过选择器传递 float

iphone - 从 UITableViewCell 到父 UITableView 的引用?

objective-c - 如何正确处理Cocoa应用程序终止?

objective-c - 无法在 NSTableView 中编辑表格单元格