如何改变在C#控制台字符串中的每个字母的前景色? [英] How to change Foreground Color of each letter in a string in C# Console?

查看:218
本文介绍了如何改变在C#控制台字符串中的每个字母的前景色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要问,如果我怎样才能改变一个特定的颜色,我想一个字符串特定字母的颜色

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

例如:

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



我想在你好红色变O。我怎么做?我知道,

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!

推荐答案

最简单的解决方案将是

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

您也可以概括成您要colorise任意字符串或字母工作的功能如下:

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.

这篇关于如何改变在C#控制台字符串中的每个字母的前景色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆