2011-11-21 31 views
1

可能重複:
How to count the number of lines in an Objective-C string (NSString)?有沒有辦法計算NSString的行數?

有沒有一種方法來計算一個的NSString的行數?

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

lines = 3;

謝謝

+0

@Patrick請SO搜索上和SO發佈問題之前,谷歌。 –

+0

你應該參考文本佈局編程指南。 [計算文本行數](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/TextLayout/Tasks/CountLines.html) –

回答

3

請嘗試下面的代碼。

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

試試這個

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

謹防componentsSeparatedByString不夠聰明MAC /窗/ 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

後一種解決方案也將正確處理CRLF序列,而'componentsSeparatedByCharactersInSet :'會爲每個這樣的序列返回一個空分量。 –

+0

謝謝@PeterHosey我認爲你說的是​​完全相反的,但我做了一些測試,你說得對。我的代碼在windows換行符上壞了。我編輯了我的答案以刪除單行示例,並更新了long/fast示例以檢查「\ r \ n」。 –

相關問題