控制台应用中的颜色

时间:2013-10-27 23:39:02

标签: vb.net colors console-application

所以我正在使用visual basic的基于控制台的应用程序,我遇到了一个问题。我正在尝试为控制台添加颜色,但只在行内添加1个字。我知道Console.ForegroundColor = ConsoleColor.Red选项,但该颜色是整行,而不是行中的1个单词。我将在下面提供一些例子。

以下是一些示例代码:

'If I use it like this the whole line will turn red
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("Hello stackoverflow, I need some help!")

如上所述,整条线变红了。如果我只想让“stackoverflow”这个词变成红色并且句子的其余部分保持正常颜色怎么办?

是否可以这样做?

先谢谢。

3 个答案:

答案 0 :(得分:4)

Console.Write("Hello ");
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("stackoverflow");
Console.ResetColor();
Console.WriteLine(", I need some help!");

您可能希望对字符串进行标记,并使用某种模式匹配函数来构建可重用的内容。

为字符串中的单个单词着色(添加处理逗号和句点的逻辑):

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

答案 1 :(得分:1)

您还可以使用字符串列表和颜色列表。字符串列表中的第一个字符串从颜色列表中获取第一个颜色,依此类推。

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

示例:

Write({"Hello ", "stackoverflow, ", "i ", "need ", "some ", "help "}, {Red, Green, Yellow, Magenta, Gray, Cyan})

答案 2 :(得分:0)

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