更改循环随机字符串中特定字符的颜色

使用 C# 控制台应用程序。


该代码旨在通过字母随机循环以尝试查找密码。当一个字母与密码中的一个字母匹配时,它将一直存在,直到所有字母都匹配。


现在,我使用“算法”作为占位符。


默认情况下,字母是红色的。


但是,我希望特定字符在匹配时将它们的(并且只有它们的)前景色更改为绿色。尚未匹配的颜色应保持红色。


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;


namespace ConsoleApp3

{

    class Program

    {


        // let's figure out how to make specific letters a specific colour.

        // if not letter, RED. if letter, CYAN.

        static void Main(string[] args)

        {

            Random r = new Random();

            string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

            List<string> dictionary = new List<string>(new string[] {

            "ALGORITHM"

        });


            string word = dictionary[r.Next(dictionary.Count)];

            List<int> indexes = new List<int>();

            Console.ForegroundColor = ConsoleColor.Red;

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < word.Length; i++)

            {

                sb.Append(letters[r.Next(letters.Length)]);

                if (sb[i] != word[i])

                {

                    indexes.Add(i);


                }

            }

            Console.WriteLine(sb.ToString());


            while (indexes.Count > 0)

            {

                int index;


                Thread.Sleep(100);

                Console.Clear();


                for (int i = indexes.Count - 1; i >= 0; i--)

                {

                    index = indexes[i];

                    sb[index] = letters[r.Next(letters.Length)];

                    if (sb[index] == word[index])

                    {


                        indexes.RemoveAt(i);





                    }



                }

                Console.WriteLine(sb.ToString());




            }


            Console.ReadLine();

        }

    }

}


杨__羊羊
浏览 118回答 1
1回答

PIPIONE

如果你想写不同颜色的字符,你需要在写每个字符之前改变颜色。例如,在您的情况下,您可以将最后一个替换为Console.WriteLine(sb.ToString());:var output = sb.ToString();for (int i = 0; i < output.Length; i++){&nbsp; &nbsp; if (indexes.Contains(i))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Console.ForegroundColor = ConsoleColor.Red;&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Console.ForegroundColor = ConsoleColor.Green;&nbsp; &nbsp; }&nbsp; &nbsp; Console.Write(output[i]);}Console.WriteLine();
打开App,查看更多内容
随时随地看视频慕课网APP