Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 537
freddiefujiwara Avatar asked Jul 06 '09 05:07

freddiefujiwara


People also ask

What does NSString mean?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+

How do you find the length of a string in Objective C?

int len = [myString length];

What is the difference between NSString and string?

NSString is class and String is struct , I understand but NSString is an reference type ,how it is working inside struct.

What is OBJC?

Objective-C is the primary programming language you use when writing software for OS X and iOS. It's a superset of the C programming language and provides object-oriented capabilities and a dynamic runtime.


2 Answers

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.

like image 190
Loda Avatar answered Sep 30 '22 21:09

Loda


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

NSString *string = @"abcde\nfghijk\nlmnopq\nrstu"; NSInteger length = [[string componentsSeparatedByCharactersInSet:                                 [NSCharacterSet newlineCharacterSet]] count]; 

Swift 4:

myString.components(separatedBy: .newlines) 
like image 43
cobbal Avatar answered Sep 30 '22 23:09

cobbal