Skip to content

Instantly share code, notes, and snippets.

@alekratz
Last active August 29, 2015 14:18
Show Gist options
  • Save alekratz/a0dcf56676a191849e7b to your computer and use it in GitHub Desktop.
Save alekratz/a0dcf56676a191849e7b to your computer and use it in GitHub Desktop.
C# colorized console output
using System;
using System.Collections.Generic;
namespace coloroutput
{
class MainClass
{
public const ConsoleColor DEFAULT = ConsoleColor.White;
public static void Main (string[] args)
{
// To use:
// put ! before words that should be red
// put @ before words that should be blue
// put # before words that should be green
Console.ForegroundColor = DEFAULT;
WriteColorLine ("@You !see some #cabinets. What do?");
WriteColorLine ("@(this entire text should be colored) while this should not");
WriteColorLine ("! that should not color anything, and in fact, should just be a single exclaimation point.");
WriteColorLine ("this is a !command");
WriteColorLine ("this is a @person");
WriteColorLine ("this is a $place");
WriteColorLine ("this is a #thing");
Console.ReadKey (true);
}
public static void WriteColorLine(string text, params object[] args)
{
Dictionary<char, ConsoleColor> colors = new Dictionary<char, ConsoleColor> {
{ '!', ConsoleColor.Red },
{ '@', ConsoleColor.Blue },
{ '#', ConsoleColor.Green },
{ '$', ConsoleColor.Magenta }
};
// TODO: word wrap, backslash escapes
text = string.Format(text, args);
string chunk = "";
bool paren = false;
for (int i = 0; i < text.Length; i++) {
char c = text [i];
if (colors.ContainsKey (c) && StringNext(text, i) != ' ') {
Console.Write (chunk);
chunk = "";
if (StringNext (text, i) == '(') {
i++; // skip past the paren
paren = true;
}
Console.ForegroundColor = colors [c];
} else if(paren && c == ')') {
paren = false;
Console.ForegroundColor = DEFAULT;
} else if (Console.ForegroundColor != DEFAULT) {
Console.Write (c);
if(c == ' ' && !paren)
Console.ForegroundColor = DEFAULT;
}
else
chunk += c;
}
Console.WriteLine (chunk);
Console.ForegroundColor = DEFAULT;
}
public static char StringPrev(string text, int index)
{
return (index == 0 || text.Length == 0) ? '\0' : text[index - 1];
}
public static char StringNext(string text, int index)
{
return (index < text.Length) ? text [index + 1] : '\0';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment