获取NSString中的位置行号

时间:2016-05-07 04:45:13

标签: objective-c nsstring

假设我在字符串中有一个NSString和一个位置。

NSString *string = @"Hello\nHi\nOK\n";
int location = 6; //Should represent the letter H in "Hi"
int lineNumber = // Get line number of the character at location 6
NSLog(@"Line Number: %i",lineNumber); // 1

如何获取该字符串的行号,在上面的示例中应该是第1行?

我尝试使用lineRangeByRange:,但这只会在字符串中给我两个额外的位置:行的开头和行的结尾。

编辑:在等待答案时,我想到了并尝试了这个:

__block int lineNumber = 0;
__block int locationNumber = 0;
[string enumerateLinesUsingBlock:^(NSString * line, BOOL * stop){
    if(affectedCharRange.location > locationNumber + line.length){
        int lineLength = line.length;
        locationNumber += line.length + 1; // Added 1 to line.length to account for newline character that was not included in line
        lineNumber++;
    }else{
        *stop = YES;
    }
}];
NSLog(@"Line Number: %i",lineNumber);

当我尝试它时,这有效,但我不确定它是否会一直有效。这适用于其他类型的换行符吗?

2 个答案:

答案 0 :(得分:1)

提取目标字符位置之前的子字符串,并计算该子字符串中的换行符数:

let s = "Hello\nHi\nOK\n" as NSString
let loc = 6
let before = s.substringToIndex(loc)
let whatLine = before.componentsSeparatedByString("\n").count - 1 // 1, the desired answer

答案 1 :(得分:0)

怎么样:

NSString *string = @"Hello\nHi\nOK\n";
NSString *stringWithoutBreaks = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
int location = 6;
NSString *theCharacter = [NSString stringWithFormat:@"%c", [stringWithoutBreaks characterAtIndex:location - 1]];
NSLog(@"theCharacter: %@", theCharacter); // H