vb.net 控制台应用程序中的颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19625043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Color in Console Application
提问by Tahmid
So I'm working on a console based application in visual basic and I ran into a problem. I am trying add color to the console but only to 1 word within the line. I know the Console.ForegroundColor = ConsoleColor.Redoption but that color's the whole line not 1 word in the line. I will provide some examples below.
因此,我正在使用 Visual Basic 开发基于控制台的应用程序,但遇到了问题。我正在尝试向控制台添加颜色,但仅向该行中的 1 个单词添加颜色。我知道该Console.ForegroundColor = ConsoleColor.Red选项,但该颜色是整行而不是行中的 1 个单词。我将在下面提供一些示例。
Here is some sample code:
下面是一些示例代码:
'If I use it like this the whole line will turn red
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("Hello stackoverflow, I need some help!")
As said above, The whole line turn's red. What if I only want the word "stackoverflow" to be red and the rest of the sentence to stay the normal color?
如上所述,整条线变成红色。如果我只希望“stackoverflow”这个词是红色的,而句子的其余部分保持正常的颜色呢?
Is it possible to do this?
是否有可能做到这一点?
Thanks in Advance.
提前致谢。
回答by emran
Console.Write("Hello ");
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("stackoverflow");
Console.ResetColor();
Console.WriteLine(", I need some help!");
You might want to tokenize your string and use some kind of pattern matching function to build something reusable.
您可能想要标记您的字符串并使用某种模式匹配函数来构建可重用的东西。
color a single word in string (add logic to handle commas and periods):
为字符串中的单个单词着色(添加处理逗号和句点的逻辑):
private static void colorize(string expression, string word)
{
string[] substrings = expression.Split();
foreach (string substring in substrings)
{
if (substring.Contains(word))
{
Console.ForegroundColor = ConsoleColor.Red;
}
Console.Write(substring+" ");
Console.ResetColor();
}
Console.WriteLine();
}
回答by HighTechProgramming15
You can also use a string list and a color list. The first string in the string list gets the first color from the color list and so on.
您还可以使用字符串列表和颜色列表。字符串列表中的第一个字符串从颜色列表中获取第一个颜色,依此类推。
Sub Write(ByRef strings As IEnumerable(Of String), ByRef colors As IEnumerable(Of ConsoleColor))
Dim i As Integer = 0
For Each s In strings
Console.ForegroundColor = colors(i)
Console.Write(s)
i += 1
Next
End Sub
Example:
例子:
Write({"Hello ", "stackoverflow, ", "i ", "need ", "some ", "help "}, {Red, Green, Yellow, Magenta, Gray, Cyan})
回答by Tukason
Private Shared Sub colorize(ByVal expression As String, ByVal word As String)
Dim substrings() As String = expression.Split()
For Each substring As String In substrings
If substring.Contains(word) Then
Console.ForegroundColor = ConsoleColor.Red
End If
Console.Write(substring &" ")
Console.ResetColor()
Next substring
Console.WriteLine()
End Sub

