假設我在字串中有一些 ASCII 藝術作為變數表示,如下所示:
char LOGO[3][40] = {
" /$$ /$$ ",
" | $$ |__/ ",
" /$$$$$$ /$$/$$$$$$$ /$$ /$$ ",
我想$在終端中專門用綠色顯示。這樣做的經典方法是在$. 不幸的是,這是不可行的,因為我有超過三行的這個字串,手動這樣做會很累。
有沒有更可行的方法來改變字串中特定字符的顏色?
TIA
uj5u.com熱心網友回復:
如果您的目標是在終端上生成綠色字符,則無需更改徽標的定義,只需測驗字符并按要求輸出轉義序列即可:
#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;
}
uj5u.com熱心網友回復:
不確定具有可用宏的解決方案,但具有額外功能的低效解決方案如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ORIG_CHAR "$"
#define GREEN_CHAR "\033[32m$\033[0m"
#define NEW_STRING(n) str_replace( n, ORIG_CHAR, GREEN_CHAR)
char LOGO[3][40] = {
" /$$ /$$ ",
" | $$ |__/ ",
" /$$$$$$ /$$/$$$$$$$ /$$ /$$ ",
};
// You must free the result if result is non-NULL.
char *str_replace(char *orig, char *rep, char *with) {
char *result; // the return string
char *ins; // the next insert point
char *tmp; // varies
int len_rep; // length of rep (the string to remove)
int len_with; // length of with (the string to replace rep with)
int len_front; // distance between rep and end of last rep
int count; // number of replacements
if (!orig || !rep)
return NULL;
len_rep = strlen(rep);
if (len_rep == 0)
return NULL;
if (!with)
with = "";
len_with = strlen(with);
ins = orig;
for (count = 0; tmp = strstr(ins, rep); count) {
ins = tmp len_rep;
}
tmp = result = malloc(strlen(orig) (len_with - len_rep) * count 1);
if (!result)
return NULL;
while (count--) {
ins = strstr(orig, rep);
len_front = ins - orig;
tmp = strncpy(tmp, orig, len_front) len_front;
tmp = strcpy(tmp, with) len_with;
orig = len_front len_rep; // move to next "end of rep"
}
strcpy(tmp, orig);
return result;
}
void main(){
for(int ii=0; ii < sizeof(LOGO)/40; ii )
printf("%s\n", NEW_STRING(LOGO[ii]));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488811.html
標籤:C 细绳 颜色 安西 ansi-colors
上一篇:C 子字串沒有給我正確的結果
下一篇:更改字串中的隨機字符
