简体   繁体   中英

How to change Foreground Color of each letter in a string in C# Console?

I want to ask if how can I change a color of a specific letter in a string with a specific color i want.

For example:

string letters = "Hello World";  //The string inputted.

I want to change "o" in the "Hello" to red. How do i do that? I know that

Console.Foreground = ConsoleColor.Red;

will change the whole string to red. What would be the best code to change a specific letter with a specific color? Thanks in advance!

The most straightforward solution would be

var o = letters.IndexOf('o');
Console.Write(letters.Substring(0, o));
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(letters[o]);
Console.ResetColor();
Console.WriteLine(letters.Substring(o + 1));

You can also generalise this into a function that works for arbitrary strings or letters you want to colorise:

void WriteLineWithColoredLetter(string letters, char c) {
  var o = letters.IndexOf(c);
  Console.Write(letters.Substring(0, o));
  Console.ForegroundColor = ConsoleColor.Red;
  Console.Write(letters[o]);
  Console.ResetColor();
  Console.WriteLine(letters.Substring(o + 1));
}

Another option might be to use a string like "Hell&o World" and parse that where & means to print the following letter in red.

string letters = "Hello World";
Char[] array = letters.ToCharArray();

foreach (Char c in array)
{
    if (c == 'o')
    {
        Console.ForegroundColor = System.ConsoleColor.Red;
        Console.Write(c);
    }
    else
    {
        Console.ForegroundColor = System.ConsoleColor.White;
        Console.Write(c);
    }
}
Console.WriteLine();
Console.Read();

I know I'm late to the party, but I found a solution that works pretty well for the original poster.

I'll give an example using a rainbow display which can be individually adapted to unique letters and colors desired in a text:

Console.ForegroundColor = ConsoleColor.Red; Console.Write("H");
Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write("e")
Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("l");
Console.ForegroundColor = ConsoleColor.Green; Console.Write("l");
Console.ForegroundColor = ConsoleColor.Blue; Console.Write("o ");
Console.ForegroundColor = ConsoleColor.DarkMagenta; Console.Write("W");
Console.ForegroundColor = ConsoleColor.Magenta; Console.Write("o");
Console.ForegroundColor = ConsoleColor.Cyan; Console.Write("r");
Console.ForegroundColor = ConsoleColor.White; Console.Write("l");
Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write("d.\n\n");
Console.ResetColor();

Hope this helps anyone else coming to find ways to individually color characters in a C# line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM