eXoDuS
eXoDuS

Reputation: 27

Is there a way to programmatically point the cursor at a specific word?

I currently have a console application that I'm using via the command line with a file .The given file now becomes a huge string .This string is split into an array of words. This array is searched with foreach for my search term. my question is now how to solve the problem that the focus is placed directly on the first word found and this word is selected.

var splittedTxt = text.Split(' ');

        if (decisionForWholeWords == true && decisionForSpelling == false)
        {
            foreach (var item in splittedTxt)
            {
                if (wordToFind.ToLower() == item.ToLower())
                {
                    Console.BackgroundColor = ConsoleColor.Red;

                    wordFound = true;
                }
                Console.Write(item);
                if (wordFound) // reset color
                {
                    Console.BackgroundColor = ConsoleColor.Black;

                    wordFound = false;
                }
                Console.Write(" ");
            }
        }

Upvotes: 0

Views: 72

Answers (2)

Elamir Ohana
Elamir Ohana

Reputation: 292

if (decisionForWholeWords == true && decisionForSpelling == false)
{
        int index = 0;
        foreach (var item in splittedTxt)
        {
            //do what you want the index.
            if (wordToFind.ToLower() == item.ToLower())
            {
                Console.BackgroundColor = ConsoleColor.Red;

                wordFound = true;
            }
            Console.Write(item);
            if (wordFound) // reset color
            {
                Console.BackgroundColor = ConsoleColor.Black;

                wordFound = false;
            }
            Console.Write(" ");

            index += item.Length;
            index += 1; //for the space
        }
    }

Upvotes: 1

fstam
fstam

Reputation: 699

You can set the cursor with a method:

Console.SetCursorPosition(x, y);

Or by using the left and top properties:

Console.CursorLeft = x;
Console.CursorTop = y;

You'll have to figure out the position of your word and set the cursor to that position.

Upvotes: 1

Related Questions