2013-10-27 30 views
1

因此,我正在開發基於控制檯的應用程序,並且遇到了一個問題。我正在嘗試向控制檯添加顏色,但僅限於該行中的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
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(); 
} 
+0

啊哈,我真的很愚蠢。不能相信我忘了Console.Write()。謝謝! – Tahmid

+0

你說什麼這種標記化的東西? – Tahmid

+0

使用正則表達式分割字符串,然後爲匹配着色。我會在一秒內爲您發佈更新。在此期間,你能接受我的回答嗎? – heavyhorse

0

你也可以使用一個字符串列表和一個顏色列表。字符串列表中的第一個字符串從顏色列表中獲取第一個顏色,依此類推。

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

私人共享子上色))(BYVAL表達作爲字符串,BYVAL字作爲字符串) 昏暗子(作爲字符串= 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