What is simpliest way to get Line number from char position in String?

前端 未结 4 1462
旧巷少年郎
旧巷少年郎 2020-12-15 11:45

What is simpliest way to get Line number from char position in String in C#? (or get Position of line (first char in line) ) Is there any built-in function ? If there are n

4条回答
  •  爱一瞬间的悲伤
    2020-12-15 11:50

    A slight variation on Jan's suggestion, without creating a new string:

    var lineNumber = input.Take(pos).Count(c => c == '\n') + 1;
    

    Using Take limits the size of the input without having to copy the string data.

    You should consider what you want the result to be if the given character is a line feed, by the way... as well as whether you want to handle "foo\rbar\rbaz" as three lines.

    EDIT: To answer the new second part of the question, you could do something like:

    var pos = input.Select((value, index) => new { value, index })
                   .Where(pair => pair.value == '\n')
                   .Select(pair => pair.index + 1)
                   .Take(line - 1)
                   .DefaultIfEmpty(1) // Handle line = 1
                   .Last();
    

    I think that will work... but I'm not sure I wouldn't just write out a non-LINQ approach...

提交回复
热议问题