为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
杨__羊羊 2022-07-10 10:01:21
使用 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();        }    }}
查看完整描述

1 回答

?
PIPIONE

TA贡献1829条经验 获得超9个赞

如果你想写不同颜色的字符,你需要在写每个字符之前改变颜色。例如,在您的情况下,您可以将最后一个替换为Console.WriteLine(sb.ToString());:


var output = sb.ToString();


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

{

    if (indexes.Contains(i))

    {

        Console.ForegroundColor = ConsoleColor.Red;

    }

    else

    {

        Console.ForegroundColor = ConsoleColor.Green;

    }


    Console.Write(output[i]);

}


Console.WriteLine();


查看完整回答
反对 回复 2022-07-10
  • 1 回答
  • 0 关注
  • 117 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号