Search code examples
c#stringconsolecoordinates

Finding index of a string through coordinates


I'm developing a screen for Windows Console project and have been struggling with the following problem.

Scenario:

  • I have a string printed in the console (it can be printed at any starting position)
  • I have variables storing the coordinates (x,y) where the string starts
  • I have the length of the printed string.

I'm trying to guess at what position of the string the cursor is.

Example:

  • The string started at position (Console.CursorLeft, Console.CursorTop), let's say (30,14)
  • The max X per row is Console.WindowWidth, let's say 50.
  • The string is 250 characters long, that means that string ended at position (30,19)

If I move the cursor to a random position (3,16) I would like to be able to calculate the corresponding index/position of the string.

I tried different formulas, euclidean distance won't work here because the string goes row per row. I have started this function from scratch several times, now I need to start from 0 again.

If anyone could advise me on the formula I should use I will appreciate it

public static int GetStringIndex(int startX, int startY, string text)
        {
            int index = -1;
            int currentX = Console.CursorLeft;
            int currentY = Console.CursorTop;


            return index;
        }

Solution

  • If I understand you correctly, this is what you want:

    int current = currentX + currentY * Console.BufferWidth;
    int start = startX + startY * Console.BufferWidth;
    
    return start <= current && current < start + text.Length ? current - start : -1;
    

    It's easy when you think of the console as a big one-dimensional array.