4

我想问我是否可以用我想要的特定颜色更改字符串中特定字母的颜色。

例如:

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

我想将“Hello”中的“o”更改为红色。我怎么做?我知道

Console.Foreground = ConsoleColor.Red;

会将整个字符串更改为红色。用特定颜色更改特定字母的最佳代码是什么?提前致谢!

4

3 回答 3

8

最直接的解决方案是

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));

您还可以将其概括为适用于您想要着色的任意字符串或字母的函数:

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));
}

另一种选择可能是使用类似的字符串"Hell&o World"并解析 where&意味着以红色打印以下字母。

于 2012-06-22T04:50:56.433 回答
1
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();
于 2012-06-22T04:53:59.103 回答
0

我知道我迟到了,但我找到了一个非常适合原始海报的解决方案。

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.

于 2020-03-06T00:50:38.003 回答