Search code examples
cstringcolorsansi-escapeansi-colors

Change colour of specific characters in string in C


Say I have some ASCII art in string presented as a variable as follows:

    char LOGO[3][40] = {
    "   /$$    /$$                       ",
    "  | $$   |__/                       ",
    " /$$$$$$  /$$/$$$$$$$ /$$   /$$     ",

I want to specifically show the $ with a green colour within the terminal. The classic way of doing so is using ANSI escape codes between an instance/s of $. Unfortunately, this is not viable since I have much more than three lines of this string, and it would be exhausting to do so manually.

Is there a much more viable way of changing the colour of specific characters within a string?

TIA


Solution

  • If your goal is to produce green characters on the terminal, you do not need to change the definition of the logo, just test the characters and output the escape sequences as required:

    #include <stdio.h>
    
    char const LOGO[3][40] = {
        "   /$$    /$$                       ",
        "  | $$   |__/                       ",
        " /$$$$$$  /$$/$$$$$$$ /$$   /$$     ",
    };
    
    int main() {
        int green = 0;
        for (size_t row = 0; row < sizeof(LOGO) / sizeof(LOGO[0]); row++) {
            for (size_t col = 0; col < sizeof(LOGO[0]) / sizeof(LOGO[0][0]); col++) {
                char c = LOGO[row][col];
                if (c == '$') {
                    if (!green) {
                        green = 1;
                        printf("\033[32m");
                    }
                } else {
                    if (green) {
                        green = 0;
                        printf("\033[0m");
                    }
                }
                putchar(c);
            }
            if (green) {
                green = 0;
                printf("\033[0m");
            }
            putchar('\n');
        }
        return 0;
    }