Search code examples
stringkotlincolors

Output a String to console with a specific color


Look at this simple piece of code:

var name = "Alex"
println(name)

Is there a way to assign a color to the string without making changes in println command? In other words, only the name variable could be shown in (say) green color instead of default white color.


Solution

  • You can use ANSI escape code to add a color to strings. To print a green string, use "\u001b[32m".

    fun main() {
        val greenColor = "\u001b[32m"
        val reset = "\u001b[0m" // to reset color to the default
        val name = greenColor + "Alex" + reset // Add green only to Alex
        println(name)
    }
    

    For more information, read https://en.wikipedia.org/wiki/ANSI_escape_code#Colors