Skip to main content
Log In | Register

News

Topic: C# Console Colored Text Method (Read 873 times) previous topic - next topic

C# Console Colored Text Method

Method will make anything between "{" "}" a color.
Example colortext("Hello {World!} ",Console.Color.Green,true);
will print "Hello World!" with "World!" being a designated color
Code: [Select]
public static void colortext(string txt, ConsoleColor color, bool newline)
        {
            int pFrom = txt.IndexOf("{") + "{".Length;
            int pTo = txt.LastIndexOf("}");
            String word = txt.Substring(pFrom, pTo - pFrom);
            int pFrom1 = txt.IndexOf("") + "".Length;
            int pTo1 = txt.LastIndexOf(word);
            String firstH = txt.Substring(pFrom1, pTo1 - pFrom1);
            int pFrom2 = txt.IndexOf(word) + word.Length;
            int pTo2 = txt.LastIndexOf("");
            String lastH = txt.Substring(pFrom2, pTo2 - pFrom2);
            foreach (var c in firstH)
            {
                if (c.ToString() == "{" || c.ToString() == "}")
                { firstH = firstH.Replace(c.ToString(), ""); }
            }
            Console.Write(firstH);
            Console.ForegroundColor = color;
            Console.Write(word);
            Console.ResetColor();
            foreach (var c in lastH)
            {
                if (c.ToString() == "{" || c.ToString() == "}")
                { lastH = lastH.Replace(c.ToString(), ""); }
            }
            Console.Write(lastH);
            if (newline)
            { Console.Write(Environment.NewLine); }
        }