Possible Duplicate:
How to count the number of lines in an Objective-C string (NSString)?
Is there a way to count the number of lines of a NSString ?
NSString * myString = @"line 1 \n line 2 \n";
lines = 3;
thanks
Possible Duplicate:
How to count the number of lines in an Objective-C string (NSString)?
Is there a way to count the number of lines of a NSString ?
NSString * myString = @"line 1 \n line 2 \n";
lines = 3;
thanks
Beware componentsSeparatedByString
is not smart enough to detect between mac/windows/unix line endings. Separating on \n
will work for windows/unix line endings, but not classic mac files (and there are some popular mac editors which still use these by default). You should really be checking for \r\n
and \r
.
Is addition, componentsSeparatedByString:
is slow and memory hungry. If you care about performance, you should repeatedly search for newlines and count the number of results:
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);
Try the following code.
NSString * myString = @"line 1 \n line 2 \n";
NSArray *list = [myString componentsSeparatedByString:@"\n"];
NSLog(@"No of lines : %d",[list count]);
Try this
NSString * myString = @"line 1 \n line 2 \n";
int count = [[myString componentsSeparatedByString:@"\n"] count];
NSLog(@"%d", count);