【问题标题】:Coloring matching substring in strstr()strstr() 中的着色匹配子字符串
【发布时间】:2015-02-12 16:44:09
【问题描述】:
这里是 C 的初学者。
我知道strstr() 可用于查找字符串是否包含某个子字符串,并且printf() 可以显示彩色输出(如下所述:stdlib and colored output in C)。
我想弄清楚的是一种仅对字符串的匹配部分着色的简单方法(如grep),因为strstr()从比赛。或者,我可以打印整个匹配行,但最终会导致整行都被着色。
假设粗体 = 为说明目的着色,我在搜索子字符串 elephant 时想要的结果是:
这是大象的獠牙
printf + 着色 strstr() 输出给出:
象牙
当然 printf + 为整个匹配的行着色:
这是象牙
提前感谢您的帮助。
【问题讨论】:
标签:
c
colors
printf
substring
strstr
【解决方案1】:
最简单的解决方案是将打印过程分成三部分。如果 strstr 返回非 NULL 结果,则打印从初始字符串开始到到达 strstr 结果的字符数。然后对 strstr 结果着色,直到匹配“针”的长度。然后打印大海捞针中未着色的剩余部分:
const char *color_start, *color_end;
print_head = haystack;
color_start = strstr (haystack, needle);
color_end = color_start + strlen (needle) - 1;
while (*print_head) {
if (print_head == color_start) { /* init color change */ }
else if (print_head == color_end) { /* revert color change */ }
putchar (*print_head++);
}
更高效的版本是:
const char *color_start, *color_end;
print_head = haystack;
color_start = strstr (haystack, needle);
color_end = color_start + strlen (needle) - 1;
while (print_head < color_start)
putchar (*print_head++);
/* init color change */
while (print_head <= color_end)
putchar (*print_head++);
/* revert color change */
while (*print_head)
putchar (*print_head++);
效率更高,因为它在每个循环中只测试一个条件,而不是每个循环最多三个条件。
【解决方案2】:
这是因为strstr 从手册中返回指向needle 中haystack 中第一次出现的指针
NAME
strstr, strcasestr - locate a substring
SYNOPSIS
#include <string.h>
char *strstr(const char *haystack, const char *needle);
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <string.h>
char *strcasestr(const char *haystack, const char *needle);
DESCRIPTION
The strstr() function finds the first occurrence of the substring
needle in the string haystack. The terminating null bytes ('\0') are
not compared.
The strcasestr() function is like strstr(), but ignores the case of
both arguments.
RETURN VALUE
These functions return a pointer to the beginning of the located
substring, or NULL if the substring is not found.
所以这是正确的输出,如果你想要那个结果,你必须使用strtok。