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?
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+
int len = [myString length];
NSString is class and String is struct , I understand but NSString is an reference type ,how it is working inside struct.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With