【问题标题】:How to change the color of an interpolated string?如何更改内插字符串的颜色?
【发布时间】:2016-07-26 04:13:21
【问题描述】:

我想要一个用户输入值,我会将其保存到一个字符串中,然后将该字符串插入到控制台输出中。有没有办法让插值字符串改变颜色。我知道使用 Console.Background/ForegroundColor,但是到目前为止,它们已经改变了整个输出的颜色。 最好的帮助是如果有某种方法可以利用类似于

的代码

Console.WriteLine($"This would be the {string}."

并让 {string} 成为不同的颜色,但我会加入任何有效的东西。

【问题讨论】:

  • 您是否考虑过使用 Console.Write() 代替(每次调用结束时没有换行符)并将您的字符串分成单独的调用?
  • 在写入特定颜色文本后使用resetcolor.......dotnetperls.com/console-color

标签: c# console console-application


【解决方案1】:

希望这对你有用

string letters = $"This would be the {string}."
string ColoredLetters = {string}; // Whatever is your string
Char[] array = letters.ToCharArray();
void WriteLineWithColoredLetter(string letters, char c) 
{
    var NormalWrite = letters.IndexOf(c);
    Console.Write(letters.Substring(0, NormalWrite));
    Console.ForegroundColor = ConsoleColor.Red;
    Console.Write(ColoredLetters);
    Console.ResetColor();
    Console.WriteLine(letters.Substring(NormalWrite + 1));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 2019-02-18
    相关资源
    最近更新 更多