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 no such function is it good solution to write extension like :
public static class StringExt {
public static int LineFromPos(this String S, int Pos) {
int Res = 1;
for (int i = 0; i <= Pos - 1; i++)
if (S[i] == '\n') Res++;
return Res;
}
public static int PosFromLine(this String S, int Pos) { .... }
}
?
Edited: Added method PosFromLine
A slight variation on Jan’s suggestion, without creating a new string:
Using
Takelimits 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:
I think that will work… but I’m not sure I wouldn’t just write out a non-LINQ approach…