Question: I have a text file from which I read the text in lines. Also from all that text I need to find the longest sentence and find in which line it begins. I have no trouble finding the longest sentence but the problem arises when I need to find where it begins.

**The contents of the text file is:**

> 
> V. M. Putinas  
> 
>  Margi sakalai  
> 
>  Lydėdami gęstančią žarą vėlai  
> 
>  Pakilo į dangų;;, margi sakalai.  
> 
>  Paniekinę žemės vylingus sapnus,  
> 
>  Padangėje ištiesė,,; savo sparnus.  
> 
>  Ir tarė margieji: negrįšim į žemę,  
> 
>  Kol josios kalnai ir pakalnės aptemę.  
> 
> 
> 
> 

My code:

```
static void Sakiniai (string fv, string skyrikliai)
{
    char[] skyrikliaiSak = { '.', '!', '?' };
    string naujas = "";
    string[] lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));

    foreach (string line in lines)
    {
        // Add lines into a string so I can separate them into sentences
        naujas += line;   
    }

    // Separating into sentences
    string[] sakiniai = naujas.Split(skyrikliaiSak); 

    // This method finds the longest sentence
    string ilgiausiasSak = RastiIlgiausiaSakini(sakiniai); 
}

```

From the text file the longest sentence is: `"Margi sakalai Lydėdami gęstančią žarą vėlai Pakilo į dangų;;, margi sakalai"`

How can I find the exact line where the sentence begins?

Answer: 
What about a nested `for` loop? If two sentences are the *same* length, this just finds the *first* one.

```
var lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));
var terminators = new HashSet<char> { '.', '?', '!' };
var currentLength = 0;
var currentSentence = new StringBuilder();
var maxLength = 0;
var maxLine = default(int?);
var maxSentence = "";

for (var currentLine = 0; currentLine < lines.Count(); currentLine++)
{
    foreach (var character in lines[currentLine])
    {
        if (terminators.Contains(character))
        {
            if (currentLength > maxLength)
            {
                maxLength = currentLength;
                maxLine = currentLine;
                maxSentence = currentSentence.ToString();
            }

            currentLength = 0;
            currentSentence.Clear();
        }
        else
        {
            currentLength++;
            currentSentence.Append(character);
        }
    }
}

```
First find the start index of the longest sentence in the whole content

```
int startIdx = naujas.IndexOf(ilgiausiasSak);

```

then loop the lines to find out which line the startIdx falls in

```
int i = 0;
while (i < lines.Length && startIdx >= 0)
{
    startIdx -= lines[i].Length;
    i++;
}
// do stuff with i

```

i is where the longest sentence starts at. e.g. i=2 means it start from the second line