Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

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

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] == '
') Res++;
        return Res;                
    }

    public static int PosFromLine(this String S, int Pos) { .... }

}

?

Edited: Added method PosFromLine

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

var lineNumber = input.Take(pos).Count(c => c == '
') + 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 bar baz" 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 == '
')
               .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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...