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

后端 未结 3 1724
执笔经年
执笔经年 2020-12-14 16:26

I want to count the lines in an NSString in Objective-C.

  NSInteger lineNum = 0;
  NSString *string = @\"abcde\\nfghijk\\nlmnopq\\nrstu\";
  NSInteger lengt         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-14 16:52

    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)
    

提交回复
热议问题