How to change Foreground Color of each letter in a string in C# Console?
c#, console
Solution
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.
Problem
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!